Tracking Memory Allocations

The Microsoft Foundation Class Library (MFC) defines the macro DEBUG_NEW to assist you in locating memory leaks. You can use DEBUG_NEW everywhere in your program that you would ordinarily use the new operator.

Note   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 C Run-Time Debug Libraries.

When you compile a debug version of your program, DEBUG_NEW keeps track of the file name and line number for each object that it allocates. Then, when you call DumpAllObjectsSince, as described in the topic Dumping All Objects, each object allocated with DEBUG_NEW will be shown with the file and line number where it was allocated, thus allowing you to pinpoint the sources of memory leaks.

When you compile a release version of your program, DEBUG_NEW resolves to a simple new operation without the file name and line number information. Thus, you pay no speed penalty in the release version of your program.

To use DEBUG_NEW

  • Define a macro in your source files that replaces new with DEBUG_NEW, as shown here:

    #define new DEBUG_NEW
    

    Note   While the framework uses DEBUG_NEW in debug builds, your code does not. You must enable this feature, as shown in this procedure.

    You can then use new for all heap allocations. The preprocessor will substitute DEBUG_NEW when compiling your code. In the Win32 Debug version of the library, DEBUG_NEW will create debugging information for each heap block. In the release version, DEBUG_NEW will resolve to a standard memory allocation without the extra debugging information.

See Also   Detecting Memory Leaks