0

I am trying to use std::allocate_shared with boost pool allocator, the programs runs fine except it crashes with segfault in shared pointer destructor after some time. I am wondering whether my implementation has a bug. i am pasting the allocator here, I am using gcc-7.2 compiler on ubuntu. please advise.

#pragma once
#include <memory>
#include <utility>
#include <boost/pool/pool_alloc.hpp>
#include <assert.h>
#include <cstddef>
#include <type_traits>
#include <scoped_allocator>

template <typename T = void>
struct _shpAllocator
{
    template <typename U> friend struct _shpAllocator;
    using value_type = T;
    using pointer = T *;
    using propagate_on_container_copy_assignment = std::true_type;
    using propagate_on_container_move_assignment = std::true_type;
    using propagate_on_container_swap = std::true_type;
    using is_always_equal = std::true_type;

    explicit _shpAllocator() {}
    template <typename U> _shpAllocator(_shpAllocator<U> const & rhs) {}

    pointer allocate(std::size_t n)
    {

        std::cerr<<"_shpAllocator() typename : "<<typeid(T).name()<<std::endl;
        auto p = __fpAlloc.allocate ( n );
        return p;
    }

    void deallocate(pointer p, std::size_t n)
    {

        __fpAlloc.deallocate ( p, n );
        return;
    }
    template <typename U> bool operator==(_shpAllocator<U> const & rhs) const { return true; }
    template <typename U> bool operator!=(_shpAllocator<U> const & rhs) const { return false; }

    private:
    static boost::pool_allocator<T, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex> __fpAlloc;
    static sLock __lock;
};

template<typename T> boost::pool_allocator<T, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex> _shpAllocator<T>::__fpAlloc;
template<typename T> sLock _shpAllocator<T>::__lock;

template<typename T> using shpAllocator = std::scoped_allocator_adaptor<_shpAllocator<T>>;
template<typename T> using sharedObjectAllocator = shpAllocator<T>;

crash trace.

Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x0000000000767cc5 in std::_Sp_counted_ptr_inplace<
Ravikumar Tulugu
  • 1,702
  • 2
  • 18
  • 40
  • I removed some unnecessary parts of code like locks etc to make it readable and clear. – Ravikumar Tulugu Mar 28 '18 at 04:26
  • I have further debugged it and found out that the object is being returned to heap when the reference count becomes 0, it should ideally return it back to the pool from which is allocated. i am not sure what else is missing in the above code. – Ravikumar Tulugu Mar 28 '18 at 08:51

0 Answers0