Tuesday, June 28, 2011

Memory leaks - part 1

I wanted to do a short series on detecting memory leaks. Microsoft has released several great tools for the detection of memory leaks, the first we'll look at is UMDH (user-mode dump heap). I'll start off my saying these posts are probably most beneficial to developers. You'll need the symbols and eventually the source code to find and fix memory leaks. If you don't have these at most you can use UMDH to confirm a given program is leaking memory.

To use UMDH you'll need umdh.exe and gflags.exe, both of which are included with WinDbg in the Debugging Tools for Windows. The first thing you need to do is make sure your symbols are correct and loaded. Create a local symbol folder and download all the symbols for both Microsoft and your code into it. Set the environment variable _NT_SYMBOL_PATH to C:\Symbols (or whatever your path is). Also, set the environmental variable OANOCACHE to 1. This forces COM and OLE to not reuse previously allocated memory which causes false positives with UMDH.

Next we need to enable stack traces. To do this use the command "gflags.exe /I myapp.exe +ust" Replace myapp.exe with the name of the application you're interested in. Do not put the full path to the executable, just the filename. When you're done you can disable stack tracing with "gflags.exe /I myapp.exe -ust"

You're now ready to actually run your app and check for memory leaks. UMDH detects memory leaks by means of snapshots. When you run UMDH it takes a "snapshot" of all the memory allocations of that process. You can then compare two snapshots and it will display the differences. To take a snapshot use the following command: umdh.exe -p:XXXX -f:snapshot1.txt (where XXXX is the process Id of the process to check). After you've taken two snapshots you can compare the two with this command: umdh.exe snapshot1.txt snapshot2.txt -f:results.txt

Next time I'll talk about how to analyze the output. I'll also talk about tips to maximize the accuracy of your results.

No comments:

Post a Comment