Delete and delete [] are the same when deleting ar

2019-04-09 13:29发布

Possible Duplicates:
How could pairing new[] with delete possibly lead to memory leak only?
( POD )freeing memory : is delete[] equal to delete?

Using gcc version 4.1.2 20080704 (Red Hat 4.1.2-48). Haven't tested it on Visual C++.

It seems that delete and delete [] works the same when deleting arrays of "simple" type.

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.

But, when deleting arrays of "complex" type, delete will cause memory leak.

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!!!

My questions are:

  1. In the first test case, why delete and delete [] are the same under g++?
  2. In the second test case, why g++ doesn't handle it like the first test case?

7条回答
放荡不羁爱自由
2楼-- · 2019-04-09 13:50

delete and delete[] seemingly being equivalent in g++ is pure luck. Calling delete on memory allocated with new[], and vice versa, is undefined behaviour. Just don't do it.

查看更多
登录 后发表回答