Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use `operator delete[]` for a single element array allocation?

Tags:

c++

If we allocate an object of size 1 as below

int *arr = new int[1];

Should we delete the object using operator delete[] or operator delete?

The reason I am concerned is if the compiler would be smart enough to convert the statement as a single element allocation int *arr = new int which would cause calling operator delete[] UB.

User Case:

I have a pointer, which I would end up allocation in a varied ways but would finally like to get it deleted. So was wondering, for single element allocation, if I consistently use int *arr = new int[1] can I consistently and safely use operator delete[]

Note

Can you please refer me back to the standards to support your answer?

like image 683
Abhijit Avatar asked Jul 12 '13 07:07

Abhijit


2 Answers

You must use delete[] and not delete. The compiler is not allowed to change new int[1] to new int.

(As int is a POD type it's quite possible that new int and new int[1] do exactly the same thing under the covers, but if this is the case then delete[] on and int* and delete on an int* will also do exactly the same thing.)

ISO/IEC 14882:2011 5.3.5 [expr.delete] / 2:

In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (1.8) representing a base class of such an object (Clause 10). If not, the behavior is undefined.

As int[1] is an array object, if you try and delete it with delete and not delete[], the behavior is undefined.

like image 134
CB Bailey Avatar answered Sep 20 '22 14:09

CB Bailey


The rule is quite simple:

  1. always balance a new with a delete
  2. always balance a new[] with a delete[]

otherwise you get undefined behaviour.

There are no exceptions; even new[1] must be balanced with a delete[], and new[0] must be deleted as the compiler can still reserve storage.

like image 26
Bathsheba Avatar answered Sep 23 '22 14:09

Bathsheba