I would like to know why in the following code the first delete won’t free the memory:
#include <list>
#include <stdio.h>
struct abc {
long a;
abc() {
puts("const");
}
~abc() {
puts("desc");
}
};
int main() {
std::list<abc*> test;
abc* pA = new abc;
printf("pA: 0x%lX\n", (unsigned long int)pA);
test.push_back(pA);
abc* pB = test.back();
printf("pB: 0x%lX\n", (unsigned long int)pB);
delete pB; // just ~abc()
test.pop_back();
delete pA; // ~abc() and free (works)
puts("before double-free");
delete pA; // ~abc() and second free (crash)
return 0;
}
Output is:
const
pA: 0x93D8008
pB: 0x93D8008
desc
desc
before double-free
desc
*** glibc detected *** ./test: double free or corruption (fasttop): 0x093d8008 ***
...
I tried it with free() also but same behavior.
These
deletestatements are not needed once you writedelete pB. You’ve a misconception thatdelete pBonly calls the destructor. No, it calls the destructor and also deallocates the memory.Also, since you’ve already written
delete pB, the next two furtherdeleteexpressions invoke undefined behavior, which means anything can happen : the program may or may not crash!Have a look at these topics: