Share via


Detecting Memory Leaks

A memory leak occurs when you allocate memory on the heap and never deallocate that memory to make it available for reuse, or if you mistakenly use memory that has already been allocated. This is a particular problem for programs that are intended to run for extended periods. In a long-lived program, even a small incremental memory leak can compound itself; eventually all available memory resources are exhausted and the program crashes. Traditionally, memory leaks have been very hard to detect.

The Microsoft Foundation Class Library (MFC) provides classes and functions you can use to detect memory leaks during development. Basically, these functions take a snapshot of all memory blocks before and after a particular set of operations. You can use these results to determine if all memory blocks allocated during the operation have been deallocated.

The size or length of the operation you choose to bracket with these diagnostic functions is arbitrary. It can be as small as a single program statement, or it can span the entry and exit from the entire program. Either way, these functions allow you to detect memory leaks and identify which memory blocks have not been deallocated properly.

Note   MFC automatically dumps all leaked objects when your program exits. As of MFC version 4.0, MFC uses the same debug heap and memory allocator as the C run-time library. For more information, see Memory Management and the Debug Heap.

This section covers the following topics: