Is it safe to delete a void pointer?

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

.


It's not a good idea and not something you would do in C++. You are losing your type info for no reason.

Your destructor won't be called on the objects in your array that you are deleting when you call it for non primitive types.

You should instead override new/delete.

Deleting the void* will probably free your memory correctly by chance, but it's wrong because the results are undefined.

If for some reason unknown to me you need to store your pointer in a void* then free it, you should use malloc and free.


It depends on "safe." It will usually work because information is stored along with the pointer about the allocation itself, so the deallocator can return it to the right place. In this sense it is "safe" as long as your allocator uses internal boundary tags. (Many do.)

However, as mentioned in other answers, deleting a void pointer will not call destructors, which can be a problem. In that sense, it is not "safe."

There is no good reason to do what you are doing the way you are doing it. If you want to write your own deallocation functions, you can use function templates to generate functions with the correct type. A good reason to do that is to generate pool allocators, which can be extremely efficient for specific types.

As mentioned in other answers, this is undefined behavior in C++. In general it is good to avoid undefined behavior, although the topic itself is complex and filled with conflicting opinions.


Deleting a void pointer is dangerous because destructors will not be called on the value it actually points to. This can result in memory / resource leaks in your application.