Skip to main content

C++ Is It Safe to Delete a void Pointer?

According to C++ Standard deleting a void* (void pointer) is undefined behavior. However usually the program will compile and run without any errors. Also the memory pointed by the pointer will be cleared. But deleting a void pointer will not call destructors.

Below is an extract from C++ standard section 5.3.5.

"3    In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted 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."

Obviously it's not recommended to delete void pointers and it is a bad practice. And as it will not call any destructors there can be memory leaks in your application. Some compilers will give a warning when you delete a void pointer.

If you look at the below example there won't be any memory leaks as most allocators can use internal boundary tags to know how much memory needs to be deallocated.

Now let's look at the below example. In this example as you can see deleting pBadPractice will not call the destructor of Test class. Hence dynamic memory allocated inside the class will be leaked. Deleting of pGoodPracrtice will not leak any memory as we are casting to the correct pointer type before calling delete.

My suggestion is avoid void pointers in your code as much as possible. In case if you have any legacy code which has void pointer deletions you can cast them to the correct object type to avoid memory leaks.