C++ object created with new, destroyed with free(); How bad is this?
If you call free()
, the destructor doesn't get called.
Also, there's no guarantee that new
and free
operate on the same heap.
You can also override new
and delete
to operate specially on a particular class. If you do so, but call free()
instead of the custom delete
, then you miss whatever special behavior you had written into delete
. (But you probably wouldn't be asking this question if you had done that, because you'd know what behaviors you were missing..)
In short, it is as bad as undefined behavior.
This is quiet self explanatory.
C Standard ($7.20.3.2/2) - "The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined."
Packet
has a destructor, even if you haven't explicitly declared one. It has a default destructor. The default destructor probably doesn't actually do much, but you can't count on that being the case. It's up to the compiler what it does.
new
and malloc
also may have wildly different implementations. For example, delete is always called in a context where it has perfect information about the size of the data structure it's deleting at compile time. free
does not have this luxury. It's possible that the allocator that new
is using may not store the bytes at the beginning of the memory area stating how many bytes it occupies. This would lead free
to do entirely the wrong thing and crash your program when freeing something allocated with new
.
Personally, if getting people to do the right thing or fixing the code yourself is completely impossible, I would declare my own global operator new
that called malloc
so then free
would definitely not crash, even though it would still not call the destructor and be generally really ugly.
Yes it does matter.
For memory obtained using new
you must use delete
.
For memory obtained using malloc
you must use free
.
new
and malloc
may use different data structures internally to keep track of what and where it has allocated memory. So in order to free memory, you have to call that corresponding function that knows about those data structures. It is however generally a bad idea to mix these two types of memory allocation in a piece of code.