Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming

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

4.83/5 (9 votes)
31 Aug 2010CPOL 35K  
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,
C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)