Using delete on pointer to std::list?

你。 提交于 2019-12-24 19:28:01

问题


In my program I have a pointer to a std::list object, it is allocated like so.

d_list_p = new std::list<some_type*>();

Then later in my program I delete it like so.

d_list_p->clear();
delete d_list_p;

For some reason I'm getting a Windows breakpoint triggered on the delete statement. If I break at the delete statement I see that the list exists and has a size of 0. Also, I never add an element to the list for the case that throws an error (I think).

The code is being compiled with the MS VC++ compiler for VS2005.

The error message says Windows triggered a breakpoint indicating memory corruption. The stack trace says the following.

ntdll.dll!DbgBreakPoint()   
[Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll] 
ntdll.dll!RtlpNtMakeTemporaryKey()  + 0x6735 bytes  
ntdll.dll!RtlpNtMakeTemporaryKey()  + 0x6b72 bytes  
ntdll.dll!RtlpNtMakeTemporaryKey()  + 0x7d5a bytes  
ntdll.dll!LdrAlternateResourcesEnabled()  + 0x33bd bytes    
ntdll.dll!RtlpUnWaitCriticalSection()  + 0x65b bytes    
msvcr80.dll!free()  + 0xcd bytes    
FM_Access_Library_NET.dll!std::list<FM_Access_Library::Logger_Callbacks *,std::allocator<FM_Access_Library::Logger_Callbacks *> >::`scalar deleting destructor'()  + 0x20 bytes C++

It is probably worth mentioning that this delete statement is in C++ code that is being built into a .NET DLL, so the program is running in mixed-mode.


回答1:


Is d_list_p a member of a class? And, does that class observe the Rule of Three?

If not, then (a copy of) d_list_p may have already been deleted.




回答2:


You need to iterate your list and delete all individual pointers in it too, because you're leaking them if you don't.

And why are you creating a pointer to std::list? just use std::list<mytype> mylist;




回答3:


Windows doublechecks the heap when you call delete, and so the delete line is finding the error, not creating it. The error is in the lines above.
Most heap corruption is caused by (A) calling delete too many times (B) calling the wrong form of delete, or (C) accessing a heap-allocated array out of bounds. We can see that A and B aren't the issue, so It's probably C. Find array accesses, and surround them asserts to validate the ranges.



来源:https://stackoverflow.com/questions/7351704/using-delete-on-pointer-to-stdlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!