Search code examples
c++boostshared-ptrunhandled-exception

Unhandled exception exception in boost shared_ptr destructor


I have the following code that randomly crashes my application,

for(map<_type, boost::shared_ptr<CRowHeaderEx<_type> > >::iterator itr = m_RowMap.begin(); itr != m_RowMap.end(); ++itr)
{
    boost::shared_ptr<CRowHeaderEx<_type> >  pRow = itr->second;
    time_t previoustime = pRow->get_DataReceived();
    if(currenttime - previoustime > Threshold)
    {
        listofdeletedkey.push_back(itr->first);
    }
}

The crash happens at end on the for loop in shared_ptr destructor. And this crash is random and not easily reproducible.

Exception : Unhandled exception at 0x00000752 in memory.hdmp: 0xC0000005: Access violation reading location 0x00000752.

Stack trace:

xxx.exe!boost::detail::sp_counted_base::release() Line 103  C++
xxx.exe!boost::detail::shared_count::~shared_count() Line 309   C++
xxx.exe!boost::shared_ptr<CRowHeaderEx<int> >::~shared_ptr<CRowHeaderEx<int> >()    C++
xxx.exe!CRowManagerEx<int>::PurgeRecords(int Threshold) Line 385    C++

And it crashes when the dispose() function is getting called in boost::detail::sp_counted_base::release().

void release() // nothrow
{
    if( BOOST_INTERLOCKED_DECREMENT( &use_count_ ) == 0 )
    {
        dispose();
        weak_release();
    }
}

disassembly:

        {
            dispose();
00412B57  mov         edx,dword ptr [this]  
00412B5A  mov         eax,dword ptr [edx]  
00412B5C  mov         ecx,dword ptr [this]  
00412B5F  mov         edx,dword ptr [eax+4]  
00412B62  call        edx  

edx value is here 0x00000752. that is causing the access violation.


Solution

  • And this crash is random and not easily reproducible.

    Your program is experiencing some form of memory corruption. I believe my previous post would be useful about how to identify memory corruption using WinDBG/Pageheap on Windows platform.

    https://stackoverflow.com/a/22074401/2724703

    edx value is here 0x00000752. that is causing the access violation.

    This indicates that, your are trying to access NULL pointer memory(with offset of +1874/0x752 byte). There could be several reason for this and it is not possible to understand all by looking at your current information.One of the reason could be your program is multi-threaded and some other thread is trying to release this shared memory concurrently with this thread.

    EDIT

    Following information can be found from boost documentation.

    shared_ptr objects offer the same level of thread safety as built-in types. A shared_ptr instance can be "read" (accessed using only const operations) simultaneously by multiple threads. Different shared_ptr instances can be "written to" (accessed using mutable operations such as operator= or reset) simultaneosly by multiple threads (even when these instances are copies, and share the same reference count underneath.)

    Any other simultaneous accesses result in undefined behavior.