Is it safe to delete a void pointer?

An̲̳̳drew picture An̲̳̳drew · Jun 2, 2009 · Viewed 59.6k times · Source

Suppose I have the following code:

void* my_alloc (size_t size)
{
   return new char [size];
}

void my_free (void* ptr)
{
   delete [] ptr;
}

Is this safe? Or must ptr be cast to char* prior to deletion?

Answer

anon picture anon · Jun 2, 2009

Deleting via a void pointer is undefined by the C++ Standard - see section 5.3.5/3:

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.

And its footnote:

This implies that an object cannot be deleted using a pointer of type void* because there are no objects of type void

.