Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does calling free () on a pointer allocated with 'new' cause heap corruption?

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?

like image 431
crazyx Avatar asked Aug 17 '10 18:08

crazyx


2 Answers

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 malloced.

like image 167
nategoose Avatar answered Sep 22 '22 14:09

nategoose


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().

like image 43
jpalecek Avatar answered Sep 20 '22 14:09

jpalecek