Reputation: 229
Is it true that the following yields undefined behavior:
void * something = NULL;
char * buffer = new char[10];
something = buffer;
buffer = NULL;
delete [] something; // undefined??
Do I first need to cast something
to char *
?
Upvotes: 6
Views: 714
Reputation: 2488
Yes.
From the Standard (5.3.5 Delete):
The value of the operand of delete shall be the pointer value which resulted from a previous array new-expression.72) If not, the behavior is undefined. [Note: this means that the syntax of the delete-expression must match the type of the object allocated by new, not the syntax of the new-expression. ]
In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined*.
**This implies that an object cannot be deleted using a pointer of type void* because there are no objects of type void.
Upvotes: 5
Reputation: 791729
Yes, strictly when you use delete[]
the static type of the pointer that you delete[]
must match the type of the array that you originally allocated or you get undefined behaviour.
Typically, in many implementations, delete[]
called on a void*
which is actually an array of a type that has no non-trivial destructor works, but it's not guaranteed.
delete[] buffer
or
delete[] (char*)something
would both be valid.
Upvotes: 4