Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete vs delete[] [duplicate]

Possible Duplicate:
( POD )freeing memory : is delete[] equal to delete ?

When I was taught C++, this was a long time ago. I was told to never use delete but delete[] as performing delete[] on a single object will be equivalent to delete. Knowing not to trust teachers too much I wonder, Is this true?

Is there ever a reason to call delete instead of delete[]?

I've scanned the possibly related questions in SO, but haven't found any clear answer.

like image 905
onemasse Avatar asked Nov 23 '10 11:11

onemasse


People also ask

When to use delete [] or delete?

delete is used for one single pointer and delete[] is used for deleting an array through a pointer.

How does delete [] know how much to delete?

new[] also stores the number of elements it created in the memory block (independently of malloc ), so that later delete[] can retrieve and use that number to call the proper number of destructors.

What is the effect of delete []?

The operand of delete must be a pointer returned by new , and cannot be a pointer to constant. Deleting a null pointer has no effect. The delete[] operator frees storage allocated for array objects created with new[] . The delete operator frees storage allocated for individual objects created with new .

Does delete [] work on vectors?

Yes. For each time a new[] expression is executed, there must be exactly one delete[] . If there is no delete[] , then there is a leak.


2 Answers

From the standard (5.3.5/2) :

In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a sub-object (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined.

In the second alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression. If not, the behavior is undefined.

So no : they are in no way equivalent !

like image 142
icecrime Avatar answered Oct 06 '22 07:10

icecrime


delete [] is "vector delete" and corresponds to vector new, i.e. new[].

You must use the matching pair of allocators. E.g. malloc/free, new/delete, new[]/delete[], else you get undefined behavior.

like image 38
Alex Budovski Avatar answered Oct 06 '22 07:10

Alex Budovski