Поделиться через


How to: Take Memory Snapshots

This topic applies to:

Edition

Visual Basic

C#

F#

C++

Web Developer

Express

Topic does not apply Topic does not apply Topic does not apply

Native only

Topic does not apply

Pro, Premium, and Ultimate

Topic does not apply Topic does not apply Topic does not apply

Native only

Topic does not apply

Note

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 Working with 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 Members object and call the CMemoryState::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 CMemoryState::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 Memory Statistic Viewing that will help you locate it.

See Also

Reference

_DEBUG

Other Resources

Memory Leak Detection in MFC