【发布时间】:2012-01-10 15:53:49
【问题描述】:
我想知道为什么在下面的代码中第一次删除不会释放内存:
#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;
}
输出是:
const
pA: 0x93D8008
pB: 0x93D8008
desc
desc
before double-free
desc
*** glibc detected *** ./test: double free or corruption (fasttop): 0x093d8008 ***
...
我也尝试了free(),但行为相同。
【问题讨论】:
-
您要删除同一个对象 3 次?对于每个
new,您应该有 一个 删除。 -
“为什么在下面的代码中第一次删除不会释放内存” - 确实如此。
-
内存被释放得很好......第一次时间。
-
@ronag:作为规则的一个例外:除非您将新的东西存储在智能指针中。
-
@phresnel:确实,删除是由智能指针完成的。因此,更好的定义是“除非其他人删除”。
标签: c++ pointers memory delete-operator