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?
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()
.
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.
精彩评论