C++ object created with new, destroyed with free(); How bad is this?
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.
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..)
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.