>Does anyone know a good way to test for memory leaks?

I don't know of any 3rd party utilities to do this (either freeware, shareware,
or commercial).  But it shouldn't be too hard to write small tracking functions
yourself.  If I were doing this, I'd use the magic of the preprocessor to
redirect all Memory Manager allocation and de-allocation functions to different
functions I'd written. Those different functions would remember the blocks I'd
allocated, and forget them when I de-allocated them. I would then have a query
function that would list any block still on the list.

Here's how I do it in the Palm OS Emulator.  In the Emulator, I have bottleneck
functions for allocating and de-allocating memory:

     void* RealAllocateMemory (size_t size, Bool clear, const char* file, int
line);
     void* RealReallocMemory  (void* p, size_t size, const char* file, int
line);
     void RealDisposeMemory (void* p);

These functions allocate and de-allocate the memory using platform-specific
facilities (e.g., TempNewHandle/DisposeHandle on the Mac, and malloc/free on
Windows and Unix).  They also track the allocations in the fashion I described
earlier.  Note also that they tag allocated blocks with the line of source code
(expressed as a file and a line within that file) that allocated the block.  I
then have macros (and one template function) that I use to call those memory
functions:

#define AllocateMemory(size)  \
     RealAllocateMemory(size, false, __FILE__, __LINE__)

#define AllocateMemoryClear(size)   \
     RealAllocateMemory(size, true, __FILE__, __LINE__)

#define ReallocMemory(p, size)       \
     RealReallocMemory(p, size, __FILE__, __LINE__)

template <class T>
void DisposeMemory (T*& p)
{
     if (p)
     {
          RealDisposeMemory ((void*) p);
          p = NULL;
     }
}

So, just do something similar to wrap up MemPtrNew and MemPtrFree, and you're
all set!

-- Keith Rollin
-- Palm OS Emulator engineer



Reply via email to