Undefined behavior when deleting char array trought void *

Is it true that the following behavior is undefined:

void * something = NULL; char * buffer = new char[10]; something = buffer; buffer = NULL; delete [] something; // undefined?? 

Do I need to cast something to char * ?

+6
c ++ memory-management undefined delete-operator
source share
2 answers

Yes, strictly, when you use delete[] , the static type of the pointer that you delete[] must match the type of array that you originally allocated, or you will get undefined behavior.

Typically, in many implementations of delete[] , void* is called, which is actually an array of type that does not have a non-trivial destructor, but it is not guaranteed.

 delete[] buffer 

or

 delete[] (char*)something 

will be valid.

+4
source share

Yes.

From the standard (5.3.5 Delete):

The value of the delete operand must be the value of the pointer, which is the result of the 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 highlighted by the new, and not the syntax of the new expression. ]

In the first option (delete an object), if the static type of the operand is different from its dynamic type, the static type must be the base class of dynamic operand types and the static type must have a virtual destructor or undefined behavior. In the second option (delete the array), if the dynamic type of the object to be deleted is different from its static type, the behavior is undefined *.

** This means that the object cannot be deleted using a pointer of type void *, because there are no objects of type void.

+5
source share

All Articles