On Mon, 13 Oct 2008 16:40:37 -0700 (PDT), bingo <zhn...@gmail.com>
wrote:
Hi, All:
? I'm new to C++ and get a little confused about the way to free
memory.
? It seems to me that both delete and free can do the job, then
what's the difference between them?
? Is delete used to free the memory allocated from new, and free to
free the memory allocated by malloc?
malloc and free are really just a part of the C heritage. Normally,
you should use new and delete.
As others have said, new and delete also ensure proper initialisation
and cleanup - constructor and destructor calls etc. However, even for
Plain Old Data (POD), you should never free memory that was allocated
with new, and you should never delete memory that was allocated with
malloc.
The reason is that new and delete may use different pools of memory to
malloc and free, meaning that mixing your calls can potentially cause
memory corruption on the heap (or rather heaps).
In practice, new will normally use the same heap as malloc - but not
always. For example, when using multithreading, sometimes each thread
will have its own heap to speed up memory management. In situations
like this, you need to write code that's as "normal" as possible
(unless there are specific rules to the contrary) or else you risk
falling into all kinds of holes. Freeing your memory in an unexpected
way definitely qualifies. Depending on how your runtimes are
implemented, it could easily bypass a mechanism that associates that
memory with the heap it came from.
Thanks a lot. You guys are really helpful.