1

为什么此代码片段在为构造函数设置时遇到段错误,而在不设置所述参数的情况下运行良好?min_alloc_sizeboost::pool<>

这是代码片段:

#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, 0, 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
4

1 回答 1

1

只需添加即可-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);

或类似的。

住在科利鲁

于 2021-07-19T12:06:53.530 回答