<分区>
Possible Duplicates:
How could pairing new[] with delete possibly lead to memory leak only?
( POD )freeing memory : is delete[] equal to delete?
使用 gcc 版本 4.1.2 20080704(Red Hat 4.1.2-48)。还没有在 Visual C++ 上测试过它。
似乎 delete
和 delete []
在删除“简单”类型的数组时效果相同。
char * a = new char[1024];
delete [] a; // the correct way. no memory leak.
char * a = new char[1024];
delete a; // the incorrect way. also NO memory leak.
但是,当删除“复杂”类型的数组时,delete
会导致内存泄漏。
class A
{
public:
int m1;
int* m2; // a pointer!
A()
{
m2 = new int[1024];
}
~A()
{
delete [] m2; // destructor won't be called when using delete
}
};
A* a = new A[1024];
delete [] a; // the correct way. no memory leak.
A* a = new A[1024];
delete a; // the incorrect way. MEMORY LEAK!!!
我的问题是:
- 第一个测试用例,为什么
delete
和delete[]
在g++下是一样的? - 在第二个测试用例中,为什么g++不像第一个测试用例那样处理它?</li>