Export (0) Print
Expand All

How to: Take Memory Snapshots 

This topic applies to:

Visual Studio Edition

Visual Basic

C#

C++

J#

Express

No

No

Native

No

Standard

No

No

Native

No

Pro/Team

No

No

Native

No

NoteNote

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Visual Studio Settings.

This topic shows how to take snapshots of memory to help locate a memory leak.

To detect a memory leak

  1. Create a CMemoryState object and call the Checkpoint member function. This creates the first memory snapshot.

  2. After your program performs its memory allocation and deallocation operations, create another CMemoryState object and call Checkpoint for that object. This gets a second snapshot of memory usage.

  3. Create a third CMemoryState object and call its Difference member function, supplying as arguments the two previous CMemoryState objects. If there is a difference between the two memory states, the Difference function returns a nonzero value. This indicates that some memory blocks have not been deallocated.

    This example shows what the code looks like:

    // Declare the variables needed
    #ifdef _DEBUG
        CMemoryState oldMemState, newMemState, diffMemState;
        oldMemState.Checkpoint();
    #endif
    
        // Do your memory allocations and deallocations.
        CString s("This is a frame variable");
        // The next object is a heap object.
       CPerson* p = new CPerson( "Smith", "Alan", "581-0215" );
    
    #ifdef _DEBUG
        newMemState.Checkpoint();
        if( diffMemState.Difference( oldMemState, newMemState ) )
        {
            TRACE( "Memory leaked!\n" );
        }
    #endif
    

    Notice that the memory-checking statements are bracketed by #ifdef _DEBUG / #endif blocks so that they are compiled only in Win32 Debug versions of your program.

    Now that you know a memory leak exists, you can use another member function, CMemoryState::DumpStatistics, to view memory statistics that will help you locate it.

See Also

Reference

_DEBUG

Other Resources

Memory Leak Detection in MFC

Community Additions

ADD
Show:
© 2014 Microsoft