Tuesday, July 3, 2007

Purifier - Detecting and Isolating Memory Leaks

The ability to dynamically allocate and deallocate memory is one of the strongest features of C/C++ programming, but the greatest strength can also be the greatest weakness.


This is certainly true of C/C++ applications, where memory-handling problems are among the most common bugs. One of the most subtle and hard-to-detect bugs is the memory leak — the failure to properly deallocate memory that was previously allocated. A small memory leak that occurs only once may not be noticed, but programs 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.


Memory leak report


Fortunately, this library provide you with effective means for detecting and identifying memory leaks. To understand how Purify library detect memory leaks using the C++ facilities, read the following topics:


Tracking of new and delete

First of all the memory leak diagnostic's redefine new and delete operations

void* operator new(unsigned int nSize,unsigned short* wszFileName,int nLine );

void __cdecl operator delete(void *pvMem);

#define new new( _T(__FILE__), __LINE__)

When memory request occures new allocation tracking cell is being created and added to the linked list.
On the picture bellow you can see the structure of this list.

Allocation Tracking mechanism


Enabling Memory Leak Detection

There are 3 steps to enable memory leak detection for your application:

1 - Define MEMPURIFY definition in project settings
2 - Make sure that the include first file your source file are including is Purify.h
3 - Define once! in the global scope (or at first line in the code be: GarbageCollector() )


Conclusion is that you have include only Purify.h file to make your application memory trackable.

1 comment:

Bijayani said...

Hi,

I happened to see your post find it quite informative. I would like to share a link where a software engineer has shared a tip on "Enabling memory leak detection in

VC++".

Here is the link:
http://www.mindfiresolutions.com/Enabling-memory-leak-detection-in-VC-44.php

hope you find it useful and of assistance.

Thanks,
Bijayani