Click here to Skip to main content
15,885,141 members
Articles / General Programming
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.83/5 (9 votes)
31 Aug 2010CPOL 33.5K   3   6
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)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 3 not useful after Skott Meyers' "Effe... Pin
halex20057-Oct-10 8:47
halex20057-Oct-10 8:47 
GeneralReason for my vote of 3 Reading "effective c " book solve t... Pin
halex20057-Oct-10 8:38
halex20057-Oct-10 8:38 
GeneralIt would be interesting to add that early in C++ days there ... Pin
Nemanja Trifunovic30-Sep-10 5:30
Nemanja Trifunovic30-Sep-10 5:30 
GeneralThere is a common myth among programmers that it's a good id... Pin
Aescleal30-Aug-10 0:13
Aescleal30-Aug-10 0:13 
GeneralSorry. I just modified the tip. Thank you Pin
elitehussar29-Aug-10 20:40
elitehussar29-Aug-10 20:40 
GeneralI am sure, what are you trying to do!? inline text mentioned... Pin
ThatsAlok29-Aug-10 20:29
ThatsAlok29-Aug-10 20:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.