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?
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.
The rule is quite simple:
new
with a delete
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With