Object Dumps
This topic applies to:
Edition |
Visual Basic |
C# |
F# |
C++ |
Web Developer |
---|---|---|---|---|---|
Express |
Native only |
||||
Pro, Premium, and Ultimate |
Native only |
In an MFC program, you can use CMemoryState::DumpAllObjectsSince to dump a description of all objects on the heap that have not been deallocated. DumpAllObjectsSince dumps all objects allocated since the last CMemoryState::Checkpoint. If no Checkpoint call has taken place, DumpAllObjectsSince dumps all objects and nonobjects currently in memory.
Note
Before you can use MFC object dumping, you must enable How to: Enable Memory Diagnostics.
Note
MFC automatically dumps all leaked objects when your program exits, so you do not need to create code to dump objects at that point.
The following code tests for a memory leak by comparing two memory states and dumps all objects if a leak is detected.
Legacy Code Example
if( diffMemState.Difference( oldMemState, newMemState ) )
{
TRACE( "Memory leaked!\n" );
diffMemState.DumpAllObjectsSince();
}
The contents of the dump look like this:
Dumping objects ->
{5} strcore.cpp(80) : non-object block at $00A7521A, 9 bytes long
{4} strcore.cpp(80) : non-object block at $00A751F8, 5 bytes long
{3} strcore.cpp(80) : non-object block at $00A751D6, 6 bytes long
{2} a CPerson at $51A4
Last Name: Smith
First Name: Alan
Phone #: 581-0215
{1} strcore.cpp(80) : non-object block at $00A7516E, 25 bytes long
Robust Programming
The numbers in braces at the beginning of most lines specify the order in which the objects were allocated. The most recently allocated object has the highest number and appears at the top of the dump. See Object Dump Interpretation for a more detailed analysis of this example.
To get the maximum amount of information out of an object dump, you can override the Dump member function of any CObject-derived object to Object Dump Customization.
You can set a breakpoint on a particular memory allocation by setting the global variable _afxBreakAlloc to the number shown in the braces. If you rerun the program the debugger will break execution when that allocation takes place. You can then look at the call stack to see how your program got to that point.
The C run-time library has a similar function, _CrtSetBreakAlloc, that you can use for C run-time allocations.