Search code examples
boostmemory-pool

Setting the `min_alloc_size` for the constructor for `boost::pool<>` encounter segment fault whereas it works well without the said parameter?


Why this code snippet encounter segment fault when setting the min_alloc_size for the constructor for boost::pool<> whereas it works well without setting the said parameter?

Here is the code snippet:

#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;
}

Here is the output:

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

Solution

  • Simply adding -fsanitize=address,undefined reveals:

    ==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
    

    The problem seems to be that next_size multiplies the partition size. Indeed, the default value is "only" 32. You probably meant the behaviour you get with

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

    or similar.

    Live ON Coliru