Does it actually work on some compilers/machines but on others it causes heap corruptions and crashes?
Does anyone have any insight into what going on under the covers?
C++ wants to call a destructor on the object when you use delete
, but passing it to free
doesn't allow this to happen. If the object contained other objects then those objects' destructors would not be called either. If the object had pointers in it then those wouldn't get freed.
Additionally C++'s new
and delete
could actually request a larger amount of memory from malloc
and use the extra for book keeping (like storing the address of the destructor function), and so the pointer you passed to free
would not actually be one that was malloc
ed.
The standard says you have to match the allocation/deallocation function perfectly (new
-delete
, new[]
-delete[]
, malloc
-free
). Theoretically, it is quite possible that some compilers implement operator new()
as a simple malloc()
, so it wouldn't cause a crash, but "only" skipping the destructor call (which is bad by itself). However, operator[]
may store the number of elements in the allocated chunk of memory in which case, the address returned by new[]
points inside some block allocated by malloc()
(not to the beginning), which means you can't free it with free()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With