Void Pointers and Object Deletion
In C , void pointers can be used to store addresses of objects of any type. A common question arises: can we safely delete objects through a void pointer?
The Problem:
Consider the following code:
void* my_alloc(size_t size) { return new char[size]; } void my_free(void* ptr) { delete [] ptr; }
Here, my_alloc allocates a char array and returns a void pointer. my_free attempts to delete the object pointed to by the void pointer.
The Answer:
Deleting an object through a void pointer without casting is undefined behavior according to the C Standard (5.3.5/3). This means that the behavior can vary across compilers and platforms.
The reason for this undefined behavior is that the compiler cannot determine the actual type of the object being deleted. As a result, it's impossible to guarantee that the correct destructor will be called, potentially leading to memory corruption or other unexpected behavior.
Safe Approach:
To safely delete objects through a void pointer, it must be cast to the original pointer type that allocated the object. This ensures that the correct destructor is called and that any resources associated with the object are properly cleaned up.
For example, in the code above, the deletion should be done as follows:
char* ptr = (char*)my_alloc(size); delete [] ptr;
The above is the detailed content of Can I Safely Delete Objects Through a Void Pointer in C ?. For more information, please follow other related articles on the PHP Chinese website!