11.2 Detecting Memory Leaks

A memory leak occurs when you allocate memory on the heap and never delete that memory to make it available for reuse. This is a particular problem for programs that are intended to run for extended periods (typically weeks or months). In a long-lived program, even a small incremental memory leak can compound itself, so that 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 provides classes and functions that 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 of the operation that 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 your entire program. Either way, these functions will allow you to detect memory leaks and identify the memory blocks that have not been deallocated.