为 `boost::pool<>` 的构造函数设置 `min_alloc_size` 遇到段错误,而它在没有上述参数的情况下运行良好?

问题描述

为什么在为 min_alloc_size 的构造函数设置 boost::pool<> 时此代码 snippet encounter错误,而它在不设置所述参数的情况下运行良好?

这是代码片段:

#include <boost/pool/pool.hpp>
#include <iostream>
int main()
{
    boost::pool<> pool_a(1024*128);
    boost::pool<> pool_b(1024*128,5*1024*1024);
    auto get_mem_blk = [](boost::pool<>& pool)
    {
        char* ptr = (char*)pool.ordered_malloc();
        pool.ordered_free(ptr);
        //memset(ptr,128 * 1024);
    };
    get_mem_blk(pool_a);   //works well
    std::cout << "pass first test" << std::endl;
    get_mem_blk(pool_b);   //segment fault!
    std::cout << "pass second test" << std::endl;
}

输出如下:

pass first test
bash: line 7:  8617 Segmentation fault      (core dumped) ./a.out

解决方法

只需添加 -fsanitize=address,undefined 即可显示:

==26122==ERROR: AddressSanitizer: allocator is out of memory trying to allocate 0xa000000010 bytes
    #0 0x7fe4dd7d3b3f in operator new[](unsigned long,std::nothrow_t const&) (/usr/lib/x86_64-linux-gnu/libasan.so.6+0xb4b3f)
    #1 0x5577f383c5b8 in boost::default_user_allocator_new_delete::malloc(unsigned long) /home/sehe/custom/boost_1_76_0/boost/pool/pool.hpp:97
    #2 0x5577f383c5b8 in boost::pool<boost::default_user_allocator_new_delete>::ordered_malloc_need_resize() /home/sehe/custom/boost_1_76_0/boost/pool/pool.hpp:733

==26122==HINT: if you don't care about these errors you may set allocator_may_return_null=1
SUMMARY: AddressSanitizer: out-of-memory (/usr/lib/x86_64-linux-gnu/libasan.so.6+0xb4b3f) in operator new[](unsigned long,std::nothrow_t const&)
==26122==ABORTING

问题似乎是 next_size 乘以分区大小。实际上,默认值是“仅”32。您可能指的是您获得的行为

boost::pool<> pool_b(1024 * 128,5 * 8);

或类似的。

Live ON Coliru