This is a mirror of official site: http://jasper-net.blogspot.com/

Detecting memory leaks using the CrtDbg Library

| Thursday, March 18, 2010
Memory is a very important aspect for an application to run. Applications that leak large amounts of memory or leak progressively may display symptoms ranging from poor (and gradually decreasing) performance to running out of memory completely. Worse, a leaking program may use up so much memory that it causes another program to fail, leaving the user with no clue to where the problem truly lies. In addition, even harmless memory leaks may be symptomatic of other problems.

When an application is very big, it could have having 100+ files and 1000+ functions and it would be tough to find memory leaks in the application, so we can use the CrtDbg Library APIs to find the memory leaks in that application.

For memory leak detection, we have so many tools available in the market, but for them you need to pay a lot. This article talks about a C Runtime Library which is free and available with all Windows OSs, and is called the CrtDbg Library. This library provides APIs which can be used to detect memory leaks.

Using the code

We can use CrtDbg library functions to detect the memory leaks in our application.

The 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:
Collapse

_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:
Collapse

_CrtMemCheckpoint(&s1);

After calling _CrtMemCheckpoint(&s1), code can be written in which we can detect the memory leak. (_CrtMemCheckpoint can be used anywhere in the code.)

After writing your code, use _CrtMemCheckpoint( &s2 ) to take another snapshot of the memory at that time; after that, you can call _CrtMemDifference(&s3, &s1, &s2).

_CrtMemDifference compares two memory states s1 and s2, and returns their differences (debug version only). _CrtMemDifference(&s3, &s1, &s2) will return 0 if there is no memory leak between the s1 and s2 memory checkpoints, and returns 1 if the code written between the checkpoints s1 and s2 has a memory leak.

Read more: Codeproject

Posted via email from jasper22's posterous

0 comments: