views:

97

answers:

2

Hello!

Is it correct that 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 * ?

Thank you!

+2  A: 

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.

Charles Bailey
+5  A: 

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.

sinec
It's not just the value of the operand it's the type as well, see the next paragraph in 5.3.5 (3).
Charles Bailey
@Charles Bailey Fixed.
sinec