Detecting Memory Leaks in C

Environment: Any console-based C code.

Introduction

CMemLeak is a small tool for detecting memory leaks in C programs. It does not replace and is not as good as the commercially available tools. However, it is free and can be used in any environment.

CMemLeak will not detect:

  • Array bounds Reads
  • Free Memory Reads
  • Stack Violations
  • Stack corruption

CMemLeak only traces the following calls:

  • malloc
  • free
  • realloc
  • calloc
  • strdup

It does this by redefining these routines. An example of usage can be seen in the test program LeakTest.c. If the program terminates normally, a report will be printed in the file CMemLeak.txt. It does this by using atexit. This means that, if the program exits using _exit, the report will have to be forced by explicitly calling XWBReportFinal.

Usage

  1. Just include CMemLeak.h in all your source files and CMemLeak.c in your code. If _DEBUG is defined, the memory leak code will be activated.
  2. An alternative: #include CMemLeak in malloc.h. Then, there is no need to include it in all the files and it will be automatically included in the files that use malloc.

Warning

The program may run a lot slower if there are lots of allocations and deallocations.

Tracking Heap Corruption

Call XWBNoFree() at the start of the program. Then, call XWBReport at key points. If the program crashes because the heap is getting corrupted, call XWBNoFree(), followed by XWBPreallocate(500), where 500 is the number of allocations you expect before the crash. If it is insufficient, CMemLeak will automatically grow the allocation buffer at the risk of itself getting corrupted.

Customization

CMemLeak works on certain patterns being set in memory. No single pattern can be unique; every so often, the data will be the same as the pattern chosen.

  • Guards for checking illegal memory writes. These are put at the end of the memory block. If the program writes outside its allocated memory, the guard will not contain this value.
    static const char xwbProtect[] = "DeAd";
  • Uninitialized memory. This value is used just after a memory block has been allocated. Pick a value that will cause the most problems. VC++ uses 0xCC.
    static const unsigned char xwbUninit = 0x55;
  • Clean memory. This value is used just after a memory block has been deallocated. Pick a value which will cause the most problems.
    static const unsigned char xwbFreed = 0xAA;
  • Report file.
    static const char xwbReportFilename[] = "CMemLeak.txt";

Understanding the Leak Report

The leak report uses a 3-letter abbreviation to indicate the type of leak, as described in the following table.

Abbreviation Name Description
FNH Free Non Heap Memory Caused by freeing memory that has already been freed, freeing memory that should not be freed, freeing memory that has not been allocated with malloc, and so forth
FMW Free Memory Write Writing to memory after it has been freed
IMW Illegal Memory Write Writing outside an allocated block. Basically, the guards have been trampled
MLK Memory Leak A straight memory leak

Sample Leak Report

In the report below, as well as a memory leak, the heap is being corrupted on line 45. The second column shows the address of the allocated memory, or, if it was freed/reallocated, the identifier.

DummyTest: after allocations
MLK: 00431D50 40 bytes allocated D:\algo\memleak\leaktest.c: 33
MLK: 00431C50 40 bytes allocated D:\algo\memleak\leaktest.c: 34
MLK: 00431BA0 40 bytes allocated D:\algo\memleak\leaktest.c: 35
Total allocations    : 3
Max memory allocation: 120 (0K)
Total leak           : 120

FNH: ok deallocated D:\algo\memleak\leaktest.c: 45
IMW: imw allocated D:\algo\memleak\leaktest.c: 34
   : imw deallocated D:\algo\memleak\leaktest.c: 48

Final Report
MLK: 00431BA0 40 bytes allocated D:\algo\memleak\leaktest.c: 35
MLK: 00431640 32 bytes allocated D:\algo\memleak\leaktest.c: 72
MLK: 00431AF0 40 bytes allocated D:\algo\memleak\leaktest.c: 94
...
Total allocations    : 113
Max memory allocation: 812 (0K)
Total leak           : 760

Downloads

Download demo project - 15 Kb
Download source - 7 Kb


About the Author

Unknown Unknown

Just a programmer: nothing more, nothing less.

Comments

  • Not working

    Posted by Vijay on 11/13/2012 01:21am

    If the C code has allocations as mentioned below, will the tool work? meta_data = (ABCD_meta_data *)calloc(1, sizeof(ABCD_meta_data)); Some how, I'm getting report like this, Final Report Total allocations : 0 Max memory allocation: 0 (0K) Total leak : 0 Please help.

    Reply
  • I use Deleaker

    Posted by MastAvalons on 01/05/2012 03:25am

    While author does do an admirable job of showing how to catch memory leaks, my personal favorite tool for the job is still Deleaker. Just personal preference.

    • SWE

      Posted by Alex on 09/27/2012 02:27pm

      It doesn't work in x64 mode!

      Reply
    Reply
  • Could try zeus virtual machine

    Posted by codejock on 09/21/2010 03:23am

    Folks, there's this new player in the market whose product is said to detect concurrency & memory errors. A friend of mine has seen a demo and seems it does a good job. The tool is called Zeus virtual machine. Look up www.parallocity.com

    Reply
  • good

    Posted by Legacy on 02/12/2003 12:00am

    Originally posted by: tang

    good

    Reply
  • I'd recommend ccmalloc

    Posted by Legacy on 02/11/2003 12:00am

    Originally posted by: Eric Espie

    Hi,

    I have tried several free memory checkers and found that ccmalloc <http://www.inf.ethz.ch/personal/biere/projects/ccmalloc/>; is very simple to use because you don't have to change your sources (no include to add), you just have to link with an additionnal object.

    The very interesting feature of ccmalloc is that the call stack can be displayed in case of memory leak.
    When you use 3rd party libraries that perform memory allocation, it is convenient to know where it was called from.

    Eric Espie.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • On-demand Event Event Date: October 23, 2014 Despite the current "virtualize everything" mentality, there are advantages to utilizing physical hardware for certain tasks. This is especially true for backups. In many cases, it is clearly in an organization's best interest to make use of physical, purpose-built backup appliances rather than relying on virtual backup software (VBA - Virtual Backup Appliances). Join us for this webcast to learn why physical appliances are preferable to virtual backup appliances, …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds