Click here to Skip to main content
Click here to Skip to main content

Memory leak finder

By , 22 Feb 2012
 

Sample Image - Memory_leak_finder.jpg

Introduction

Have you ever had a memory leak? Wished you knew where you allocated it and how? Is your boss cheap and refuses to buy Boundchecker or another debugging tool?

Here is the solution for you. A memory leak detector compiled directly into your code. It reports memory leaks with call stack of the allocation down to a user defined depth.

As an add-on, it does simple checks of the memory before and after the memory block, to track buffer overwrites.

Usage

Include tracealloc.cpp in your project. Define DETECT_LEAKS in the project settings. Compile. Run your application. Memory leaks are reported into your debug output window when the application terminates. Just click the memory leak and the correct file and line will be shown.

You can find further instructions in the source code.

How is it done?

The code overrides operator new and operator delete. For each allocation made, the code allocates extra space for tracking, call stack and no-mans-land. The current call stack is fetched and remembered, finally the code puts the newly allocated block in a linked list and the requested memory is returned.

When a memory block is deleted, the header is found and checked for buffer overwrites. The memory block is then removed from the linked list and deallocated.

When the program terminates, the global memory tracker object is deleted. The destructor traverses the linked list for memory blocks that isn’t deleted (= leaked memory). It then fetches symbol information for the call stacks and dumps the information in the debug console.

Limitations

The code is Microsoft Visual Studio and Win32 specific. It requires a debug build. The code is C++ specific. It handles new/delete but not malloc/free. The code will run slower with leak detection active (roughly at half normal debug build speed).

Finally

I want to thank Zoltan Csizmadia who wrote ExtendedTrace. I have used parts of his code for stack walking and symbol lookups.

I also want to thank the Code Project community. I have found many solutions or pointers in the right direction here. I hope I have given something back with this contribution.

Thank you!

History

February 22, 2012:

  • Inclusion of contributed bug fixes (author acknowledged in read me file)
  • Upgrade of solution to Visual Studio 2010.

License

This article, along with any associated source code and files, is licensed under The MIT License

About the Author

Erik Rydgren
Software Developer (Senior)
Sweden Sweden
Member
B.Sc in Software engineering
 
Writing software for the finance market.
Languages known: C/C++, SQL, Java, Perl, M68000 assembly and more. Give me the syntax and I'll program in it.
 
In my spare time i like to watch movies, read books and play computergames.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: Code now upgraded to Visual Studio 2008memberErik Rydgren16 Apr '09 - 22:59 
Only the dll version of the source is upgraded to latest code.
The dll version can however be used for all projects and it is a simple task to modify it if a monolithic executable is needed.
GeneralLinker ErrorsmemberSuper Garrison14 Jan '08 - 14:10 
I got 9 linker errors. The first one is:
nafxcwd.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new(unsigned int,char const *,int)" (??2@YAPAXIPBDH@Z) already defined in tracealloc.obj
 
Can someone help me?
 
I'm using VC.NET 2002 with SP1, added tracealloc.cpp only to my project and recompiled. I also added to ignore nafxcwd.lib in Ignore specific library in the Linker
 
Thanks
Garrison
GeneralRe: Linker Errorsmembermatakk@126.com10 Oct '08 - 18:22 
Hi,Thanks
I got this error too.
I create a project with VS 2008 , MFC shared dll , unicode.
How tell linker that i use the source code function ,replace the dll function?
 

1>Linking...
1>tracealloc.obj : error LNK2005: "void __cdecl operator delete(void *)" (??3@YAXPAX@Z) already defined in mfc90ud.lib(mfc90ud.dll)
1>tracealloc.obj : error LNK2005: "void __cdecl operator delete[](void *)" (??_V@YAXPAX@Z) already defined in msvcrtd.lib(MSVCR90D.dll)
1>Build log was saved
1>operator_new_overload_test_mfc - 2 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 2 up-to-date, 0 skipped ==========
GeneralRe: Linker ErrorsmemberErik Rydgren12 Oct '08 - 20:29 
You need to force the compiler to accept multiple declarations of a function by setting an argument to the linker as: /FORCE:MULTIPLE. This will make the compiler ignore all subsequent declarations of a function. Just make sure that the linker finds the tracealloc versions of new and delete first.
 
The instructions for this scenario is described in the sourcecode.
GeneralThanks.membermark-w12 Sep '07 - 14:55 
Works well.
GeneralCompile errors in VC8memberDavid_Leikis5 Jun '07 - 9:16 
I am using VC8 and am getting some errors during compile.
 
memleakfinder\tracealloc.cpp(246) : error C2440: '=' : cannot convert from 'const char *' to 'LPTSTR'
 
This is also errored on line 258 as well as 246. Any suggestions?
 
Also, there is an undefined 'i' error at line 547 because of the new scope requirements.
 
I fixed it with a define at line 545 with a "size_t i;" and removed the define in the for loop:
 
bool AssertMem(char* m, char c, size_t s)
{
size_t i;
for (i = 0; i < s; i++)
if (m[i] != c) break;
return i >= s;
}
 
I await your response to the first problem, please...
 
Regards,
David Leikis
GeneralRe: Compile errors in VC8memberDavid_Leikis5 Jun '07 - 9:26 
I fixed the compile errors, but wanted you to know all of the details...
 
I fixed the LPTSTR error simply by casting the return to:
 
lpszParamSep = (LPTSTR)_tcschr( lpszParsed, _T(',') );
 
I hope that this helps.
 

I will now be trying to use your code. Thank you for your efforts! I hope this helps me find my leaks.
 
David Leikis
GeneralTrouble in tracking memory leakmemberChandrasekar S10 Oct '05 - 2:20 
Hi
 
Can you guide me through the step by step procedure of tracking the memory leak....
 
I am not able to get how to get the memory leak tool to work for working
 
Can you help me out...
 
Thanks and Regards
ChandrasekarSmile | :)
 
Chandrasekar
GeneralMissing __cdeclmemberJoão Paulo Figueira4 May '05 - 10:05 
If you compile a DLL with the __stdcall calling convention, don't forget to add the __cdecl to the new and delete declarations.
 
I got this on my debug output:
Memory statistics
-----------------
Total allocations: 500
Max concurrent allocations: 43
Does this means I have no leaks?
 
Thanks for sharing this tool!
 
Regards,
João Paulo Figueira
Embedded MVP
GeneralFixing bugsmemberSergey Solozhentsev5 Dec '04 - 21:03 
I've solved your problem with detect leaks in dll. At first, you should add this code
....
HANDLE g_hSymInitProcess = NULL;
....
Then in InitSymInfo tou should add
DWORD dwProcessID = GetCurrentProcessId();
g_hSymInitProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessID);
 
BOOL Res = SymInitialize( g_hSymInitProcess, lpszSymbolPath, TRUE);
You cannot use GetCurrentProcess() (see MSDN for SymInitialize)
And then replace all GetCurrentProcess() with g_hSymInitProcess
In ~cLeakDetector() add CloseHandle(g_hSymInitProcess)
After that you should compile dll without exporting any additional functions. And it will detect all memory leak in dll. The same is in execitable.
 
And I want you to write about how to install debuging tools. I met with this problem and some interesting things. After install debuging tools there is the old version of dll in WinDir\System32. The same after manualy replace dll. So I found that Windows replace dbhhelp.dll if it find that this dll is not native (same for all system dll). So that you should firstly replace dbghelp.dll in dllcache folder and after that in system32 follder.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 22 Feb 2012
Article Copyright 2003 by Erik Rydgren
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid