Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined behavior on deleting char array trought void *

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 * ?

like image 852
HotHead Avatar asked Mar 23 '10 17:03

HotHead


2 Answers

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.

like image 114
sinek Avatar answered Nov 04 '22 10:11

sinek


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.

like image 38
CB Bailey Avatar answered Nov 04 '22 12:11

CB Bailey