Introduction

With this utility you can simply find memory leaks in your program (CRT and COM-Leaks!). Each leak is displayed with the callstack (including the source line) of the allocation. So, you can easily find leaks, while using the STL. It will also write a file with the callstack if your application crashes (it can also handle stack-overflows!). It almost has no runtime-overhead (runtime-cost). And the best: it is free (GNU Lesser General Public License).

Finding memory leaks

It is easy to implement this in your existing VC code:

Add Stackwalker.cpp and Stackwalker.h to your project.

Include Stackwalker.h in your main source file.

Call InitAllocCheck() right after the beginning of your main.

Call DeInitAllocCheck() just before the end of your main (here all the leaks will be reported).

All the leaks will be listed in the file YouAppName.exe.mem.log in the application directory (only in debug builds; it is deactivated for release builds). This will also activate exception-handling by default (release and debug builds).

Only use exception-handling

If you only want to use exception handing, you need to do the following:

Add Stackwalker.cpp and Stackwalker.h to your project.

Include Stackwalker.h in your main source file.

Call OnlyInstallUnhandeldExceptionFilter() right after the beginning of your main.

If an exception occurs, it will write a file with the callstack in the application directory with the name YouAppName.exe.exp.log.

Explanation

This line is the beginning of one leak. If you have more than one leak, then each leak will start with a RequestID.

RequestID

For CRT: This is the RequestID which is passed to the AllocHook. This ID clearly identifies an allocation. The CRT just increments this number for each allocation. You can also use this number with the _CrtSetBreakAlloc function.

This is an actual stack entry. The stack is shown from the last function on the top going through each callee until the end of the stack is reached.

1:

This number is incremented for each complete callstack. You can ignore this.

f:\vs70builds\9466\vc\crtbld\crt\src\dbgheap.c

The actual filename.

(359)

The line number inside the file.

+30 bytes

This is the offset from this line in bytes (if a line produces more than one assembler instruction).

(_heap_alloc_dbg)

The name of the function.

More options by calling InitAllocCheck

InitAllocCheck has three parameters:

Parameter name

Description

eAllocCheckOutput

eOutput

This is an enum for output-format. The following is possible:

ACOutput_Simple (default)

This outputs the callstack as seen above.

ACOutput_Advanced

This has a more detailed output of the callstack. For more info see here.

ACOutput_XML

This outputs the leaks in an XML file so that you can read it easily from other applications or use some XSLT to transform it to a more readable format you want. For more info see here.

BOOL

bSetUnhandledExeptionFilter (default: TRUE)

If this is set, an UnhandledExceptionFilter will be installed. If an (unhandled) exception occurs it will write the callstack in a log file and terminate. For more info see here.

ULONG

ulShowStackAtAlloc (default: 0)

Notice: This works only for CRT-allocs.

Here you can specify the level of mallocs/frees logging. By default nothing will be logged in the log file at runtime. If you need to know what happens while executing the program you can specify a value. Then the malloc/free action will be logged to the file (either with or without callstack).

You can also get an output with more info about each stack entry. For this you have to call InitAllocCheck with the first parameter set to ACOutput_Advanced. If you execute the following sample you will get a file Appication-Name.exe.mem.log with more info:

Explanation

This number is incremented for each complete callstack. You can ignore this.

5

This is the depth of the callstack. This number is incremented for each stack entry. The stack is shown from the last function on the top (number 0) going through each callee until the end of the stack is reached.

main +49 bytes

The number of bytes from the beginning of this function, where the instruction for this callstack is stored.

Mem-leak-analyse tool

If you are using the XML-output format then you can use my MemLeakTool to display the leaks in a sorted order (sorted by callstack). Just select the "xml-leak"-File and press "Read". The callstack will be displayed in a TreeView. If you select a node, the source code will be shown in the right part (if it could be found).

Information: This program requires .NET Framework 1.0!

A word on leaks

You should be aware, that some leaks might be the result of other leaks. For example the following code throws two leaks, but if you remove the "originator" of the leaks, the other leak will also disappear. For example:

The basis of the memory leak logger is a Hashtable with information about all the allocated memory (including callstack). Basically _CrtSetAllocHook is called to hook all the memory allocations / frees. Therefore only C/C++ allocations are logged. On every allocation a portion of the callstack and the Instruction-Pointer is caught and stored in the Hashtable, with some other information about the allocation.

If the application calls DeinitAllocCheck then the Hashtable will be iterated and the (saved) callstack of all the entries will be listed in the file. For this we provide a pointer to our ProcessMemoryRoutine function to the StackWalk function.

In detail

Hashtable

The Hashtable contains by default 1024 entries. You can change this value if you are doing many allocations and want to reduce the collisions. Just change the ALLOC_HASH_ENTRIES define.

As hash-key, the lRequestID for each allocation is used. This ID is passed to the AllocHook function (at least for allocs). If it is not passed (for example, for freeing), then an (valid) address is passed. By having this address it is also possible to get the lRequestID, by looking into the _CrtMemBlockHeader of the allocated block.

Insert an allocation into the Hashtable

If a new allocation should be inserted into the Hashtable, first a thread context for the actual thread is made by calling GetThreadContext. This function requires a "real" thread handle and not a pseudo handle which is returned by GetCurrentThred. So, for this I have to create a "real" handle by calling DuplicateHandle.

Actually, I only need the current Ebp and Eip registers. This could also be done by just reading the registers with the inline assembler. Now having the registers, I read the memory at the specified address. For Eip, I only need to read 4 bytes. I do not know why StackWalk needs to read the Eip values, but if the values could not be read from StackWalk it fails to build the callstack. The real important part is the callstack which is stored in the memory pointing from Ebp (or Esp).

At the moment, I just try to read 0x500 bytes by calling the ReadProcessMemory function. I don't read the complete stack, because it might use too much memory for many allocations. So, I reduced the maximum size to 0x500. If you need a deeper callstack, you can change the MAX_ESP_LEN_BUF define.

If the callstack is not 0x500 bytes deep, then the ReadProcessMemory will fail with ERROR_PARTIAL_COPY. If this happens, I need to ask how many are possible, to read without any error. For this I need to query this value by calling VirtualQuery. Then, I try to read as many bytes as possible.

Having the callstack I can simply insert the entry into the Hashtable. If the given hash-entry is already occupied, I make a linked list and append this entry to the end.

Building the leak-list

If you call DeInitAllocCheck I simply walk through the Hashtable and output every entry which was not freed. For this I call StackWalk with a pointer to my own memory-reading-function (ReadProcMemoryFromHash). This function is called from the internals of StackWalk. If it is called it looks up the Hashtable for the given lRequestID and returns the memory which was stored in the Hashtable. The lRequestID is passed in the hProcess parameter of the StackWalk function (as stated in the documentation of StackWalk).

Ignoring allocations

Allocations/frees for _CRT_BLOCK are ignored (for more info, see here). This is because CRT dynamically allocates some memory for "special purposes". The tool also checks the _CRTDBG_ALLOC_MEM_DF flag of the _crtDbgFlag variable. If it is off, then all the allocations are ignored. For more details see _CrtSetDbgFlag.

To track COM-memory-leaks, you have to provide an IMallocSpy interface. This interface must be registered with CoRegisterMallocSpy. After that the (own) IMallocSpy instance is called for every memory (re)allocation/free. So, you can track all memory actions.

The storage of the callstack is done in the same way as for CRT-allocs (in a Hashtable). So, for more info please read the CRT-section.

A word on COM-leaks

Actually, there is nothing to say, but...

If you are using MSXML 3 or 4 implementation, you have to be aware of the fact that this parser uses a "smart" pseudo-garbage collector. This means that they allocate memory and will not free it after it is used! So, you may see some leaks which are only "cached memory". If you first call CoUninitialize, then all the cached memory will be freed and the "real" COM-leaks will be reported.

MFC usage

The problem with MFC is that the derived CWinApp class is instantiated by the C-runtime, because it is a global variable. The easiest solution to implement the Leak-Finder is to declare the following staticstruct inside your MainApp.cpp.

You also have to add stackwalk.cpp and stackwalk.h to your project. You also need to add the #include<stdafx.h> on top of the stackwalk.cpp file (if you use precompiled headers). A sample of an MFC application is also available from the top of this article:

Temporarily disable logging (only CRT)

When you don't want to log a special allocation of your application (for whatever reason; MFC does this often), then you can simply deactivate it by disabling the CRT flag _CRTDBG_ALLOC_MEM_DF with the _CrtSetDbgFlag function. Here is an example of how you can do this:

Simple using

If you just call InitAllocCheck with no parameters or with the second parameter set to TRUE, then an unhandled exception filter will be installed. If an unhandled exception occurs, a log file with the callstack will be written, a dialog box with the exception message will be displayed, and the application will be terminated with FatalAppExit.

Second simple using

If you don't want the AllocCheck-overhead (the (small) overhead is only present in debug builds), you can simply call OnlyInstallUnhandeldExceptionFilter. This will install the UnhandledExceptionFilter which writes a log file if an (unhandled) exception occurs. The log file will be stored in the application directory with the name YouAppName.exe.exp.log:

Common mistakes

One of the most common mistakes while using this tool is that you statically instantiate classes in your main function. The problem is that the destructor of the class is called after the call to DeInitAllocCheck. If some memory was allocated inside this class, this memory will appear as a leak. For example:

There are two solutions for this. You can start a block after the call to InitAllocCheck and end it before the call to DeInitAllocCheck. With this you can be sure that the destructors are called before the leak file is produced. For example:

The second solution is to use the same technique that is used for MFC applications (see above).

Visual Studio 7 and Win2K / NT

I found a problem with the executables built with VS7 and run on Win2K or NT. The problem is due to an old version of dbghelp.dll. The PDB files generated from VS7 are in a newer format (DIA). It appears that the VS installations do not update dbghelp.dll on Win2K. So the original version (5.0.*) is still on the system and will be used. But with this version it is not possible to read the new PDB format. So, no callstack can be displayed.

To get it to work you have to do the following

Download the latest Debugging Tools for Windows (which includes dbghelp.dll). You have to install it to get the files. But you only need the dbghelp.dll! Now we have another problem. The installer does not replace the original dbghelp.dll. So we need to copy the dbghelp.dll in our EXE dir. Now to make sure the right version is loaded you have to put a file with the name appname.local in your EXE dir (please replace appname with the EXE name (without extension)). Now it should also work on WinNT/2K.

Known issues

The memory leak works correctly only if the lRequestID does not wrap (32-bit value). If the value wraps around, then it is not possible to clearly assign a given lRequestID to a previous allocation, because it is possible that this ID was used twice (or even more). But this happens only with VC7, because VC6 has a bug in the C-runtime which will call _DbgBreak if the lRequestID wraps (if no _CrtBreakAlloc is used).

If you compile with "Detect 64-bit portability issues (/Wp64)" option on VC7, it will generate a warning.

If you use this tool in managed C++ it will not correctly display the callstack for managed code.

For some reason, the COM-alloc-callstack cannot display the stack-entry which really calls the CoTaskMemAlloc function. Only the upper stack entry can be shown.

Nobody is engaged to maintain the articles written many years ago, just because the code would not compile with newest compiler and your warning level preferences.

You are definitively not a corporate thinking guy - instead of swich on your brain, learn something, invest a little bit of your time, improve the code to the new compiler requirements and share it here, you attack the autor, which made and share this great article with community!

I assume, you think, this is your life right to criticize other people, do nothing for other people and think, other people works only for your pleasure.

Such people as you have definitively no business being on this community.

I wanted to capture the memory leaks when I run operation/task.
I was able to call InitAllocCheck() before operation/task and DeInitAllocCheck() after operation/task. XML file generated and worked fine.

After that for another operation/task without restarting the process/application, I call InitAllocCheck() before task and DeInitAllocCheck() after the task. It doesn't capture the traces properly.
Do you know why?

Thank you for your spontaneous response.
I actually have more than 500 DLLs in my process and I wanted to capture memory leaks happening in all DLLs per operation/task.
Could you please point me to LeakFinder_RC11 help, if you have one already?

I'm using LeakFinder RC11, to figure out a memory leak in a SMTP Event Sink DLL of my own, loaded by the Windows SMTP Service on Windows 2003.
I have an exception when stopping the iisadmin service. My custom DLL is alredy unloaded, so is the leakfinder hook ?
Here is the exception stack trace:

You must not unload your DLL if you use the COM-LeakFinder... I might remember that COM has some limitations with Malloc-Hooks and unloading...
I suggest to disable the COM-Leak detection! It almost makes no sence, because COM internaly uses some "garbage collector" (see article).

Thanks for that.
I have another problem, which is that file name and line number are empty in the output of leakfinder for my own modules compiled in debug mode.
I think this is because LeakFinder is enabled in a DLL, not in an executable.
What do you think ?

After using LeakFinder-RC10 in a large project and inspecting the stack traces using MemLeakAnalyse, I've noticed that some some stack traces are missing the bottom stack frames. For example, a call to new may be 20 calls deep, but when I expand the stack trace, the stack entry for main and the function called by main are missing. Any ideas why this is happening?

The leakfinder is capturing the stack frames at runtime. And I restricted the size of the collected stackframes to 0x2000 bytes. If you need more infos, you can increase this value in
LeakFinder.cpp:1076
#define MAX_CALLSTACK_LEN_BUF 0x2000

I used the latest LeakFinder-RC10 in an application that uses template classes and functions, which results in extremely long function names. To make a long story short, LeakFinder crashed in a call to strcpy_s, because the destination buffer wasn't large enough. The quick fix is to replace each call to strcpy_s with a call to strncpy_s in StackWalker.cpp, and also #define strncpy_s strncpy.

I am trying to use leakfinder with Google Test (gtest) available at http://code.google.com/p/googletest/. Gtest has a statically initialized singleton that requires allocations on the heap. When I run leakfinder, every allocation is reported as a leak, even though it is properly deleted.

I can work around this by making the source module containing the leakfinder defines and includes the first program to be compiled. Then it only reports the two leaks allocated by gtest and not the allocations by my program. Is there something I can do so leakfinder does not have to be the first program compiled? Do you know why this problem occurs?

COM leaks should be reported, it just *starts* in my code... you need to look at the callstack a little bit up! The comment has nothing to do with this...

Of course, you need debug-symbols in order to get (correct) results! Also, starting with Vista you also need to get symbols for MS DLLs from the MS Symbols Server... most DLLs are now compiled with FPO, which makes it almost impossible to walk the callstack without (PDB) symbols.

No... VS6 has nothing to do with my leakfinder... even if you compiler your code with VS6...
You must be sure, that you use a recent/new version od dbghelp.dll! Therefor please install DebuggingToolsForWindows which contains the latest dbghelp.dll. And plase this file in the same folder as the exe.

in an other topic (Walking the callstack , Walking the callstack[^]) you offer a StackWalker.cpp, which I included in my App.
The Stackwalker.cpp here seems to be different.
Can I use this stackwalker, the stackwalker from here, too to show the callstack and have the new opportunity to search for memoryleaks ?
Will there be a problem when I change the stackwalker.h/.cpp against the files from here ?

Your LeakFinder works with Visual Studio 2010. The _CrtMemBlockHeader has not changed. There was a problem converting the Visual Studio project files however. It said it could not convert the .vcproj file. I had to create a new project and changed the preprocessor statements (_MSC_VER 1600). Once that was done it worked fine.

I noticed you moved StackWalker moved to CodePlex. Why don’t you move LeakFinder also?

I got last version of Memory-Leak (RC9). I was able to build your project with MS VC8, no problem.
After, in my project, I made the following :
- added LeakFinder.h and .cpp to my project
- added StackWalker.h and .cpp to my project
- added #define INIT_LEAK_FINDER, #define XML_LEAK_FINDER and #include <leakfinder.h> in my main.cpp file