11.3 Using DEBUG_NEW to Aid Debugging

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

When you compile a Debug version of your program, DEBUG_NEW will keep track of the filename and line number for each object that it allocates. Then when you call DumpAllObjectsSince, as described in the previous section, 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 will resolve to a simple new operation without the filename 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

You can then use new for all heap allocations. The preprocessor will substitute DEBUG_NEW when compiling your code. In the 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.