Obj *op = new Obj;
Obj *op2 = op;
delete op;
delete op2; // What happens here?
当你意外地双重删除时,最糟糕的情况是什么?这有关紧要吗?编译器会报错吗?
Obj *op = new Obj;
Obj *op2 = op;
delete op;
delete op2; // What happens here?
这会导致未定义的行为。任何事情都可能发生。实际上,我想最有可能发生的是运行时崩溃。
未定义行为。 标准没有做出任何保证。 可能您的操作系统会提供一些保证,例如“您不会破坏其他进程”,但这对您的程序帮助不大。
您的程序可能会崩溃。 您的数据可能会被损坏。 您下一个工资的直接存款可能会取走500万美元。
class Obj
{
public:
int x;
};
int main( int argc, char* argv[] )
{
Obj *op = new Obj;
Obj *op2 = op;
delete op;
delete op2;
return 0;
}
编译它 (我在使用Mac OSX 10.6.8上的gcc 4.2.1,但可能因人而异):
russell@Silverback ~: g++ so.cpp
运行它:
russell@Silverback ~: ./a.out
a.out(1965) malloc: *** error for object 0x100100080: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap
看这里,gcc运行时实际上会检测到双重删除并在崩溃之前提供相当有帮助的信息。
虽然这是未定义的:
int* a = new int;
delete a;
delete a; // same as your code
这是一个明确定义的内容:
int* a = new int;
delete a;
a = nullptr; // or just NULL or 0 if your compiler doesn't support c++11
delete a; // nothing happens!
我觉得应该发布这篇文章,因为没有人提到它。
class a {};
int main()
{
a *test = new a();
delete test;
a *test2 = new a();
delete test;
return 0;
}
*** Error in `./a.out': double free or corruption (fasttop): 0x000000000111a010 ***
class Foo { /*...*/ };
void yourCode()
{
Foo* p = new Foo();
delete p;
delete p; // DISASTER!
// ...
}
#include <iostream>
int main() {
int *x = new int;
for(size_t n = 1;;n++) {
std::cout << "delete x " << n << " time(s)\n";
delete x;
}
return 0;
}