boost shared_ptr析构函数中出现未处理的异常

Unhandled exception exception in boost shared_ptr destructor

本文关键字:未处理 异常 shared ptr 析构函数 boost      更新时间:2023-10-16

我有以下代码会随机崩溃我的应用程序

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

崩溃发生在shared_ptr析构函数中for循环的末尾。这种崩溃是随机的,不容易重现。

异常:内存中0x00000752处出现未处理的异常。hdmp:0xC0000005:读取位置0x00000 752时发生访问冲突。

堆栈跟踪:

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

当在boost::detail::sp_counted_base::release()中调用dispose()函数时,它会崩溃。

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

反汇编:

        {
            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值在此为0x00000752。导致访问违规。

这种崩溃是随机的,不容易重现。

您的程序正经历某种形式的内存损坏。我相信我之前的文章会对如何在Windows平台上使用WinDBG/Pageheap识别内存损坏很有用。

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

edx值在此为0x00000752。导致访问违规。

这表示您正在尝试访问NULL指针内存(偏移量为+1874/0x752字节)。这可能有几个原因,不可能通过查看您当前的信息来了解所有原因。其中一个原因可能是您的程序是多线程的,而其他线程正试图与此线程同时释放此共享内存。

编辑

以下信息可以从boost文档中找到。

shared_ptr对象提供与内置相同级别的线程安全性类型。shared_ptr实例可以"读取"(仅使用常量访问操作)。不同的shared_ptr实例可以"写入"(使用诸如as operator=或reset)同时由多个线程执行(即使在这些实例是副本,共享相同的引用计数下面。)

任何其他同时访问都会导致未定义的行为