Dfference between delete and delete[]

There's a common myth among Visual C++ 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; // very 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—including built-in types—yields undefined behavior. The fact that on some platforms apps 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 will work with other compilers. To conclude, using delete instead of delete[] and vice versa is a very bad programming habit that should be avoided.

No comments: