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?
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?
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.
sizeof(T*) == sizeof(U*)
for all T,U
suggests that it should be possible to have 1 non templated, void *
based garbage collector implementation. But then, when the gc actually has to delete/free a pointer exactly this question arises. To make it work, you either need lambda function destructor wrappers (urgh) or you would need some sort of dynamic "type as data" kind of thing which allows back and forth between a type and something storable. –
Conventionalize unordered_map<void*,Something>
), I figured out a - well - workable if not very memory efficient way to do it: template <class T> struct Foo { void deleter(void*p) { delete reinterpret_cast<T*>(p); } };
Then I stored a pointer to that deleter function into Something
, at the transition from typed to untyped. Arrays of T aside, this should be solid and easily extendable.. –
Conventionalize 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
.
NULL
make any difference for application memory management? –
Bosquet 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.
sizeof(T*) == sizeof(U*)
for all T,U
suggests that it should be possible to have 1 non templated, void *
based garbage collector implementation. But then, when the gc actually has to delete/free a pointer exactly this question arises. To make it work, you either need lambda function destructor wrappers (urgh) or you would need some sort of dynamic "type as data" kind of thing which allows back and forth between a type and something storable. –
Conventionalize unordered_map<void*,Something>
), I figured out a - well - workable if not very memory efficient way to do it: template <class T> struct Foo { void deleter(void*p) { delete reinterpret_cast<T*>(p); } };
Then I stored a pointer to that deleter function into Something
, at the transition from typed to untyped. Arrays of T aside, this should be solid and easily extendable.. –
Conventionalize 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.
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.
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).
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.)
delete
may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject representing a base class of such an object. If not, the behavior is undefined." So if a compiler accepts your code without a diagnostic, it's nothing but a bug in the compiler... –
Tie delete void_pointer
. It's undefined behavior. Programmers should never invoke undefined behavior, even if the response appears to do what the programmer wanted done. –
Apricot NULL
make any difference for application memory management? –
Bosquet 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.
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++.
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);
}
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;
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.
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.
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.
new
actually is defined to throw. This is not true. It is compiler and compiler switch dependent. See for example MSVC2019 /GX[-] enable C++ EH (same as /EHsc)
switches. Also on embedded systems many choose to not pay the performance taxes for C++ exceptions. So the sentence starting with "But you forfeit std::bad_alloc..." is questionable. –
Conventionalize © 2022 - 2024 — McMap. All rights reserved.
malloc
andfree
directly. That implicitly carries the fact that the constructor/destructor will not be called (as the answers below say) on whatever underlies thatvoid*
pointer. – Wigeondelete (MyPluginBase*) aPointer
and ensure thatMyPlugin
has a virtual destructor. – Stedman