Programming‎ > ‎C++‎ > ‎Programming Tips‎ > ‎Resoure Management‎ > ‎

Don't Confuse Delete with Delete []

There's a common myth among programmers that it's OK to use delete instead of delete [] to release arrays 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 [] don't crash can be attributed to sheer luck: Visual C++, for example, implements both delete[] and delete for built-in types by calling free(). However, there is no guarantee that future releases of Visual C++ will adhere to this convention. Furthermore, there's no guarantees that this code will work on other compilers. To conclude, using delete instead of delete[] and vice versa is hazardous and should be avoided.

Comments