开发者

Delete char array. Alternative way? [duplicate]

This question already has answers here: 开发者_C百科 Closed 11 years ago.

Possible Duplicate:

Is it necessary to call delete[] vs delete for char arrays?

char *p = new char[200];

delete p;

This kind of (I changed var name) code is from a big commercial project.

The third line. Is this right? Should I change it or leave it there. Coz no bug report for this and this programs runs more than 4 years.

Thanks.


You have to use delete[] since you used new[], it's not an alternative.

delete [] p;


  • If new uses [], delete must it as well:

    T *p = new T[100];
    delete [] p; //correct
    delete p   ; //incorrect
    
  • If new doesn't use [], delete must not use it as well:

    T *p = new T;
    delete [] p; //incorrect
    delete p   ; //correct
    

Incorrect doesn't mean that you will get compilation error; neither does it mean that the program must fail at runtime. It means, the program behavior is undefined; anything could be possible, and most likely there will be memory leak.


In theory, to follow the standard, line 3 should read delete[] p;.

But, in practice this has no implication, as the destructor of char does nothing.

Indeed, the difference between the delete and the array delete, is that with array delete, the destructor is called as many times as there are objects. With the regular delete, the destructor is called only once.

In the end, you should replace it with delete[] p;


You allocated an array with operator new[]. You must balance that with operator delete[], not operator delete:

delete[] p;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜