65.9K
CodeProject is changing. Read more.
Home

C++ Tip: Aware of the confusion between delete with delete[]

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.83/5 (9 votes)

Aug 30, 2010

CPOL
viewsIcon

35022

There is a common myth among C++ programmers that it is okay to use delete instead of delete [] to release dynamically allocated arrays (via new) for built-in types. For example,
int *p=new int[10];
delete p; /*bad; should be: delete[] p*/
This is totally wrong. The C++ standard specifically says that using delete to release dynamically allocated arrays of any type yields undefined behavior. The fact that, on some platforms, applications that use delete instead of delete [] do not crash; can be attributed to sheer luck. Visual C++, for instance, implements both delete[] and delete for built-in types by calling free() function. However, there is no guarantee that future releases of Visual C++ will adhere to this convention. Furthermore, there is no guarantee that this code will work on other compilers.

To conclude, using delete instead of delete[] and vice versa is hazardous and should be avoided.