tags:

views:

168

answers:

3

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?

+9  A: 

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.

nategoose
+1  A: 

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

jpalecek
+1  A: 

The new operator is also overloadable. If someone wrote a new operator that was doing something quite different, say grabbing pointers from a memory pool, calling free on those pointers could be very dangerous.

pythonic metaphor
… calling `free` on those pointers…
Potatoswatter