Export (0) Print
Expand All

Memory State Comparison

This topic applies to:

Edition

Visual Basic

C#

C++

Web Developer

Express

Topic does not applyTopic does not apply

Native only

Topic does not apply

Standard

Topic does not applyTopic does not apply

Native only

Topic does not apply

Pro and Team

Topic does not applyTopic does not apply

Native only

Topic does not apply

Table legend:

Topic applies

Applies

Topic does not apply

Does not apply

Topic applies but command hidden by default

Command or commands hidden by default.

Another technique for locating memory leaks involves taking snapshots of the application's memory state at key points. The CRT library provides a structure type, _CrtMemState, which you can use to store a snapshot of the memory state:

_CrtMemState s1, s2, s3;

To take a snapshot of the memory state at a given point, pass a _CrtMemState structure to the _CrtMemCheckpoint function. This function fills in the structure with a snapshot of the current memory state:

_CrtMemCheckpoint( &s1 );

You can dump the contents of a _CrtMemState structure at any point by passing the structure to the _CrtMemDumpStatistics function:

_CrtMemDumpStatistics( &s1 );

This function prints a dump of memory allocation information that looks like this:

0 bytes in 0 Free Blocks.
0 bytes in 0 Normal Blocks.
3071 bytes in 16 CRT Blocks.
0 bytes in 0 Ignore Blocks.
0 bytes in 0 Client Blocks.
Largest number used: 3071 bytes.
Total allocations: 3764 bytes.

To determine whether a memory leak has occurred in a section of code, you can take snapshots of the memory state before and after the section, and then use _CrtMemDifference to compare the two states:

_CrtMemCheckpoint( &s1 );
// memory allocations take place here
_CrtMemCheckpoint( &s2 );

if ( _CrtMemDifference( &s3, &s1, &s2) )
   _CrtMemDumpStatistics( &s3 );

As the name implies, _CrtMemDifference compares two memory states (s1 and s2) and produces a result (s3) that is the difference of the two states. Placing _CrtMemCheckpoint calls at the beginning and end of your program and using _CrtMemDifference to compare the results provides another way to check for memory leaks. If a leak is detected, you can use _CrtMemCheckpoint calls to divide your program and locate the leak using binary search technique.

Community Additions

ADD
Show:
© 2014 Microsoft