Detecting C++ memory leaks

Posted ten years ago

A while ago I had the problem of detecting memory leaks in my code, and I didn't want to spend lots of money on a brittle software package to do that. It's fairly simple to redefine malloc() and free() to your own functions, to track the file and line number of memory leaks. But what about the new() and delete() operators? It's a little more difficult with C++, if you want to figure out the exact line number of a resource leak.

In this article, I'll explain how you can get a stack trace for where your resource leaks occur. This method is for Microsoft Windows. Linux developers are better served with Valgrind.

Overview

We will use #define to replace the standard implementation of malloc() and free() with ones that record the file and line numbers where they are called. That way, we can track where memory leaks occur for allocations made using the standard C allocation functions.

We will overload the new() and delete() operators to track the address of the functions that they are called, by walking backwards up the stack.

Finally, we will parse the .map file generated by the linker. This will let us figure out where new() and delete() were called based on the return address information.

The header file

The first thing we'll do is have an #ifdef, because memory tracking is inefficient. You'll want to cut it out in release versions of your code.

Every *.cpp source file in your program should include this file. It's optional, of course. But if you allocate something in a memory-tracked module, and free it in another that doesn't, your program will crash, since it was allocated with _dbgmalloc() and free'd with free() instead of _dbgfree().

The add_record() and del_record() functions perform the real work of memory tracking. They will allocate the requested amount of memory, but they will add space for extra tracking information. The tracking information is stored in the first few bytes of the memory block, and then the returned pointer offset by this amount. We will also reserve extra space at the end of the memory block, so we will be able to detect writes past the end of the array. We will write a specific sequence of bytes (Here, 0x12345678) at this location, and if when the block is free'd, the bytes have been modified, then your program has done something it shouldn't have, and the del_record() function will complain.

What about new?

That's all fine and good for malloc() and free(), and strdup() and _tcsdup() and calloc() and realloc(), but what about C++? When you call malloc() above, you see that the macro puts in the file and line number information, but this is not possible for the new operator. Instead, we will do it the hard way. We'll redefine the new operator and then search up the stack for the caller's address and store that. Later, we'll parse the linker's map file to figure out which function it was from the address.

Here's the implementation for new() and delete(). They are almost the same as malloc() and free() above, except that they record the return address instead of the file and line information.

Walking the stack

Here's where the magic happens. Because file and line number information is not available to the new operator, we will walk the stack in order to record the return address. Later on, we'll figure out the function name where they were called from.

Making the map file

So far, for malloc() and free() calls, we have recorded the file and line number information, but for new() and delete() we have only the return address. How do we figure out which function called new() and delete()?

We will induce the linker to create a .map file. Add these options to your makefile when calling link.exe. Replace example with the name of your executable output file. (The debug.cpp code will assume that the map file has the same base name as the executable).

/MAP:example.map /MAPINFO:LINES

Compiler differences

Note: For Microsoft Visual Studio 2005, Microsoft has removed the MAPINFO:LINES option. So you should either use an earlier version of the compiler, or be content without line numbers. You will still have function names.

The Map File

The Map file contains a list of every function in your program, and the exact addresses to which they are loaded. So, using a binary search, we are able to look up a function given an address. I have implemented this process in Mapfile.cpp, which is called diretly from debug.cpp.

Putting it together

When your program exits, the debug.cpp module will automatically execute this cleanup code. The cleanup code will dump out any unfree'd memory chunks.

dbgprintf

To see the memory leaks, you will have to implement a debug message handler. I don't have time to explain this right now, but it should be pretty obvious from the source code. Or, you can replace dbgprint() with OutputDebugString(), or printf(), or MessageBox(), or whatever you want.

Well, when working on Windows anyway, then I can recommend the "Visual Leak Detector": it's free, works great under Visual Studio, and does provide a stack trace to where the memory leaked was allocated. All that in a format VS understand, so when running a debug build from within VS, double-clicking on the stack traces will actually take you to the code location...

Ignore Ulysses... It's much better to have the callstack available at runtime. Ulysses should feel fortunate that he hasn't had to debug anyone's code where it was necessary to have a little tool like this.

There is an advantage to having memory leak tracking built-in, instead of generating a huge log file with a separate tool. Whenever the debug version of my program exits, it performs the heap check, so I instantly know when and where a memory leak occurs during development. The MS UMDH tool is meant to be run when you suspect there is a problem, not all the time.

Reinvention is an important part of being a good programmer. When someone re-writes an existing software tool, the result is a tool that is a perfect fit for the purpose, plus new skills for the developer. Depending on the scope of the task, there may be a time savings over having to learn the existing tool and working around its bugs.

On Monday, I was pleased to be an uninvited speaker at Waterloo Devhouse, hosted in Postrank's magnificent office. After making some surreptitious alterations to their agile development wall, I gave a tongue-in-cheek talk on how C++ can fit in to a web application.

At some point in your programming career you may have to go through a graph of items and process them all exactly once. If you keep following neighbours, the path might loop back on itself, so you need to keep track of which ones have been processed already.