Is it safe to delete a void pointer?

C++Memory ManagementCastingVoid Pointers

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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

.

Solution 2 - C++

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.

Solution 3 - C++

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.

Solution 4 - C++

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.

Solution 5 - C++

The question makes no sense. Your confusion may be partly due to the sloppy language people often use with delete:

You use delete to destroy an object that was dynamically allocated. Do do so, you form a delete expression with a pointer to that object. You never "delete a pointer". What you really do is "delete an object which is identified by its address".

Now we see why the question makes no sense: A void pointer isn't the "address of an object". It's just an address, without any semantics. It may have come from the address of an actual object, but that information is lost, because it was encoded in the type of the original pointer. The only way to restore an object pointer is to cast the void pointer back to an object pointer (which requires the author to know what the pointer means). void itself is an incomplete type and thus never the type of an object, and a void pointer can never be used to identify an object. (Objects are identified jointly by their type and their address.)

Solution 6 - C++

If you really must do this, why not cut out the middle man (the new and delete operators) and call the global operator new and operator delete directly? (Of course, if you're trying to instrument the new and delete operators, you actually ought to reimplement operator new and operator delete.)

void* my_alloc (size_t size)
{
   return ::operator new(size);
}

void my_free (void* ptr)
{
   ::operator delete(ptr);
}

Note that unlike malloc(), operator new throws std::bad_alloc on failure (or calls the new_handler if one is registered).

Solution 7 - C++

A lot of people have already commented saying that no, it's not safe to delete a void pointer. I agree with that, but I also wanted to add that if you're working with void pointers in order to allocate contiguous arrays or something similar, that you can do this with new so that you'll be able to use delete safely (with, ahem, a little of extra work). This is done by allocating a void pointer to the memory region (called an 'arena') and then supplying the pointer to the arena to new. See this section in the C++ FAQ. This is a common approach to implementing memory pools in C++.

Solution 8 - C++

Because char has no special destructor logic. THIS won't work.

class foo
{
   ~foo() { printf("huzza"); }
}

main()
{
   foo * myFoo = new foo();
   delete ((void*)foo);
}

The d'ctor won't get called.

Solution 9 - C++

If you want to use void*, why don't you use just malloc/free? new/delete is more than just memory managing. Basically, new/delete calls a constructor/destructor and there are more things going on. If you just use built-in types (like char*) and delete them through void*, it would work but still it's not recommended. The bottom line is use malloc/free if you want to use void*. Otherwise, you can use template functions for your convenience.

template<typename T>
T* my_alloc (size_t size)
{
   return new T [size];
}

template<typename T>
void my_free (T* ptr)
{
   delete [] ptr;
}

int main(void)
{
	char* pChar = my_alloc<char>(10);
	my_free(pChar);
}

Solution 10 - C++

If you just want a buffer, use malloc/free. If you must use new/delete, consider a trivial wrapper class:

template<int size_ > struct size_buffer { 
  char data_[ size_]; 
  operator void*() { return (void*)&data_; }
};

typedef sized_buffer<100> OpaqueBuffer; // logical description of your sized buffer

OpaqueBuffer* ptr = new OpaqueBuffer();

delete ptr;

Solution 11 - C++

There is hardly a reason to do this.

First of all, if you don't know the type of the data, and all you know is that it's void*, then you really should just be treating that data as a typeless blob of binary data (unsigned char*), and use malloc/free to deal with it. This is required sometimes for things like waveform data and the like, where you need to pass around void* pointers to C apis. That's fine.

If you do know the type of the data (ie it has a ctor/dtor), but for some reason you ended up with a void* pointer (for whatever reason you have) then you really should cast it back to the type you know it to be, and call delete on it.

Solution 12 - C++

I have used void*, (aka unknown types) in my framework for while in code reflection and other feats of ambiguity, and so far, I have had no troubles (memory leak, access violations, etc.) from any compilers. Only warnings due to the operation being non-standard.

It perfectly makes sense to delete an unknown (void*). Just make sure the pointer follows these guidelines, or it may stop making sense:

  1. The unknown pointer must not point to a type that has a trivial deconstructor, and so when casted as an unknown pointer it should NEVER BE DELETED. Only delete the unknown pointer AFTER casting it back into the ORIGINAL type.

  2. Is the instance being referenced as an unknown pointer in stack bound or heap bound memory? If the unknown pointer references an instance on the stack, then it should NEVER BE DELETED!

  3. Are you 100% positive the unknown pointer is a valid memory region? No, then it should NEVER BE DELTED!

In all, there is very little direct work that can be done using an unknown (void*) pointer type. However, indirectly, the void* is a great asset for C++ developers to rely on when data ambiguity is required.

Solution 13 - C++

For the particular case of char.

char is an intrinsic type that does not have a special destructor. So the leaks arguments is a moot one.

sizeof(char) is usually one so there is no alignment argument either. In the case of rare platform where the sizeof(char) is not one, they allocate memory aligned enough for their char. So the alignment argument is also a moot one.

malloc/free would be faster on this case. But you forfeit std::bad_alloc and have to check the result of malloc. Calling the global new and delete operators might be better as it bypass the middle man.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAn̲̳̳drewView Question on Stackoverflow
Solution 1 - C++anonView Answer on Stackoverflow
Solution 2 - C++Brian R. BondyView Answer on Stackoverflow
Solution 3 - C++ChristopherView Answer on Stackoverflow
Solution 4 - C++JaredParView Answer on Stackoverflow
Solution 5 - C++Kerrek SBView Answer on Stackoverflow
Solution 6 - C++bk1eView Answer on Stackoverflow
Solution 7 - C++Paul MorieView Answer on Stackoverflow
Solution 8 - C++raduView Answer on Stackoverflow
Solution 9 - C++youngView Answer on Stackoverflow
Solution 10 - C++Sanjaya RView Answer on Stackoverflow
Solution 11 - C++boboboboView Answer on Stackoverflow
Solution 12 - C++zackery.fixView Answer on Stackoverflow
Solution 13 - C++rxantosView Answer on Stackoverflow