John F. Dumas Vulcan Ware
_blank_
ZMemory - A Memory Leak Detection Library (C and C++)

Source Code (linux / win32)

C++ C
Zip File Zip File

Example Usage

C++

#include "zmemory.h"

class Foo
{
};

int main()
{
   ZFILENAME("main.txt");

   // ----------------------------
   // Was: Foo *fooPtr = new Foo();
   // ----------------------------

   Foo *fooPtr = ZNEW(Foo());

   // ----------------------------
   // Was: int *ptr = new int[5];
   // ----------------------------

   int *ptr = ZNEW(int[5]);

   // ----------------------------
   // Was: delete fooPtr;
   // ----------------------------

   ZDELETE(fooPtr);

   // ----------------------------
   // Was: delete[] fooPtr;
   // ----------------------------

   ZDELETE_ARRAY(ptr);

   return(0);
}

C

#include "zmemory.h"

int main()
{
   char *s1;
   char *s2;
   char *s3;

   ZFILENAME("main.txt");

   s1 = (char *)ZMALLOC(10 * sizeof(char));
   s2 = (char *)ZCALLOC(5,   sizeof(char));
   s3 = (char *)ZMALLOC(10 * sizeof(char));

   ZFREE(s1);
   ZFREE(s2);

   s3 = ZREALLOC(s3, 1000000 * sizeof(char));

   ZFREE(s3);

   return(0);
}

After you've swapped out malloc for ZMALLOC (or new for ZNEW, etc.) throughout your code, recompile and run your program (be sure to use ZFILENAME to set the output filename).

Your output file will look something like this ...

0x804a050 malloc   main.c 12
0x804a060 calloc   main.c 13
0x804a070 malloc   main.c 14
0x804a050 free     main.c 16
0x804a060 free     main.c 17
0x804a070 refree   main.c 19
0xb7cf8008 realloc  main.c 19
0xb7cf8008 free     main.c 21
      
Sort the output, the 'sort' command line utility on windows will do the job (unix based systems have a similar utility)

      C:\>sort output.txt > sorted.txt

         

Here are the contents of 'sorted.txt' ...

         0x804a050 free     main.c 16
         0x804a050 malloc   main.c 12
         0x804a060 calloc   main.c 13
         0x804a060 free     main.c 17
         0x804a070 malloc   main.c 14
         0x804a070 refree   main.c 19
         0xb7cf8008 free     main.c 21
         0xb7cf8008 realloc  main.c 19
         
Notice that every address appears an even number of times (one free for each malloc, etc.). This is the pattern you'll see when the program in question doesn't leak memory.

On the other hand, if you find an address from an allocation that's not matched by a deallocation, you've found a memory leak (sorting the output makes these easy to spot).

This assumes you convrted all the memory allocation/deallocation calls in your program to use the Z macros, if you missed any, you can have false positives or false negatives).


Return to More C++       Return to Main