Thursday, 5 March 2009

Finding memory leaks in programs

One of the common problems programmers face is memory leaks. There is no easy way to fix them unless you use some additional programs like Rational Purify that will detect them. Luckily there is an inbuilt mechanism that can help you identify these leaks.

This identification of leaks is a two step process. In the first step we will write the code and find if there are any leaks.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
//#include <crtdbg.h> //You may need this on some compilers

using namespace
std;

int
main()
{

int
*a=new int[10]; //memory being leaked

_CrtDumpMemoryLeaks(); //this points to the memory leaked
//The above should be the last statement before return
return 0;
}


If you run the program in debug mode (using F5), you will see the memory leak in the output window.

Now you can find out the exact peice of code which caused this leak. Modify the code as follows:




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
//#include <crtdbg.h> //You may need this on some compilers

using namespace
std;

int
main()
{

//The following line should be added at the start of program
_crtBreakAlloc=56; //The number corresponds to the memory leak block
//from the output window

int
*a=new int[10]; //memory being leaked

_CrtDumpMemoryLeaks(); //this points to the memory leaked
//The above should be the last statement before return
return 0;
}



The code will break at the point the memory leak is being created.

No comments:

Post a Comment