ANSI C ++: Differences Between delete and delete []
I was looking for a sleeping set of code:
int* ip;
ip = new int[100];
delete ip;
The example above states that:
This code will work with many compilers, but it should read:
int* ip;
ip = new int[100];
delete [] ip;
Is it really so?
I am using the "Microsoft (R) 32-bit C / C ++ Compiler Optimizer for version 11.00.7022 for 80x86" compiler and do not comment (first example) at compile time. At run time, the pointer matters NULL
.
Do other compilers do it differently? Can the compiler not complain and problems can appear at runtime?
a source to share
You should always use delete []
when destroying an array as it handles calling all destructors in the content. I think the reason you are dealing here is because the type int
does not have a destructor, but when you get down to creating arrays of objects with destructors, you will actually see the difference.
It's a good argument for using std::vector
this instead, of course. It gives you it all.
a source to share
In this case, the compiler can not make a mistake in this case - the index type that is created new
and new[]
, the same. Of course, the C ++ standard does not require any diagnostics for this situation. However, your first snippet of code is wrong for all compilers and will result in undefined behavior - you won't be tempted to do this because the compiler doesn't complain.
The C ++ spec requires that you use delete [] when deleting an array, and if you are concerned about cross compiler compatibility or code that works with future versions of the same compiler, then you should use it.
Your runtime may choose to allocate memory differently for arrays than for individual objects. By incorrectly specifying what you are deleting, you run the risk that your code may not free memory correctly.
So basically, call the form you want ... !!!
a source to share