Tuesday, September 19, 2006

New/Delete Is Just a C++ Way to Manage the Heap...

Recently, a blogger asked this question: What do operators new and delete do in C++?

New/delete is just a C++ way to manage the heap. You probably remember that C run-time calls malloc/free to allocate/release memory blocks on the heap. That's C run-time way to manage the heap. Furthermore, VC++ Debug Configuration uses DEBUG_NEW to manages the heap. DEBUG_NEW is the same as new, but it adds some debug information (such as line number) to it. Following the same theme, you could override C++ new/delete with your own approach to manage the heap.

Note that internally, new/delete still calls C run-time malloc/free to perform certain tasks. Regardless, it is important to ensure that your program manages the heap consistently. For instance, if you call new to allocate a block, call delete to release it. Otherwise, the memory may get messed up.