A Developer WeBLOG RSS 2.0

The past few weeks I’ve been assigned a background task to fix memory leaks issue in our Document Comparison engine. Our document comparison engine was written in Native C++ and ported to Microsoft Visual C++ (not sure if there’s any differences between the two). As a C++ application, our document comparison engine is not managed by .NET framework. It does not have the luxury of having a Garbage Collector to automatically cleaned up all the memory pointers you have created/allocated. In a non-managed code, these memory pointers need to be cleaned manually, or otherwise you’ll be faced by the classic C++ issue: Memory Leaks.

One of the tricky bit in solving memory leaks issue in C++ application is to detect the memory leaks. That is the very first problem that must be solved. I encountered many articles to detect memory leaks, and most of them don’t work. The first article that I tried was this. It was given by my Team Leader, so I assume that this one most probably will work. After few days, I got the constructor overriding of the delete operator working, but seems to stuck in getting the overriding of the new operator to work. I decided to ditch that article to find another one. After trying a couple of other articles, I found that C++ actually has a built in way to debug memory leaks issue.

This makes memory leak detection to be an easy thing to do. All you need to do is to call _CrtDumpMemoryLeaks() function of the crtdbg class. This function will output the list of memory allocations that was created by the application. Cool! But that solved only half of the problem, because now you need to know which object that has not been disposed, in which file and which line was the object created. To solve this problem, we need to override the new operator of DEBUG_NEW and then redefine the DEBUG_NEW. To override the new operator of the debug new, add the following code to your header file:

   1: #ifdef _DEBUG
   2: #include <crtdbg.h>
   3: #define DEBUG_NEW new (_NORMAL_BLOCK, __FILE__, __LINE__)
   4: #else
   5: #define DEBUG_NEW new
   6: #endif

Then you need to add the following line in your cpp file to redefine your DEBUG_NEW:

   1: #ifdef _DEBUG
   2: #define new DEBUG_NEW
   3: #endif

After you add the above two codes, when you call the _CrtDumpMemoryLeaks() function again, it will include the filename and the line in which the code was created. Awesome! Here is an example on how it looks like:

memoryleakdumpexample

Tips: If you’re using Microsoft Visual C++, you can place the codes in your stdafx.h and stdafx.cpp files. That way you do not need to do it in every single file.

RWendi

Tuesday, February 10, 2009 1:36:22 AM UTC |  Comments [2]
c++
All Content © 2010, RWendi