If you are using C++ with MFC, there is a builtin leak detector. When you run a program in the IDE, it will print out a leak detection report in the output window when your program terminates. By default, it tells you about the leaks but does not report where the leak originated. To enable file and line information, at the top of every file where you think a leak might occur, after all "#include" and "#import" statements but before any static variables, functions or methods, add the following:
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
This will enable detection of file and line in the leak report (debug builds only).
If you don't do this, you will see something in the output window that looks like:
Detected memory leaks!
Dumping objects - > ;
{18} normal block at 0x00781248, 64 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
If you add the preamble, you will get:
Detected memory leaks!
Dumping objects - > ;
D:\workarea\LeakyProject\yadayada\yadayada.cpp(62) : {18}
normal block at 0x00781248, 64 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
If you do not use MFC, MSDN describes how to do the above
here[
^] manually. IMHO this requires much less setup than the other answers.
Additionally, if you use MFC then you can monitor memory allocations, in real-time while your application runs, using the following technique. Note that this is only available in debug builds.
As others have posted, there are far more sophisticated methods to track leaks. When it comes to leak detection during development then you should use the mechanism that is easiest to use.
#ifdef _DEBUG
AFX_ALLOC_HOOK _OldHook = NULL;
BOOL AFXAPI AllocHook(size_t nSize,BOOL bObject,LONG lRequestNumber)
{
if (_OldHook)
return _OldHook(nSize,bObject,lRequestNumber);
return FALSE;
}
void SetHook()
{
_OldHook = AfxSetAllocHook(AllocHook);
}
CMainApp::CMainApp()
{
#ifdef _DEBUG
SetHook();
#endif
}
#endif
Then after you run your code and see the leaked memory notice that you will also see the request number that created the leak. When you run your application again you can break in at this request number to see the code that is causing the leak.