Test For Memory Leak

last modified: May 3, 2006

Whats a good way to test for memory leaks? I want code that will force me to delete any objects that I create.

There are malloc replacement libraries and Valgrind and Boundschecker (and more...) - that keep track of your memory allocations and can tell you (most often at the end of the program's execution) the memory blocks that are still allocated, who allocated them, and whether pointers to the memory still exist. Another possibility is to use a garbage collection library and tell it to give errors whenever pointers to allocated memory disappears without the memory having been freed. The garbage collector could be disabled/compiled out for release builds if performance is an issue,

In TestForMemoryLeakSampleCode I thought of checking the amount of physical memory, but this doesn't seem to work.

Now I think a scheme like this would be better:

For example, the class Dog

class Dog
{
 private theAnimalData

 DogConstructor()
 {
   animalData = new AnimalData
   IncPtr(animalData)
 },

 DogDestructor()
 {
   DecPtr(animalData)
 },
},

// increments the reference count by 1
function IncPtr(thePointer)
{
 ArrayOfPointers[thePointer] = ArrayOfPointers[thePointer] + 1
},

// decrements the reference count by 1 and call delete if count is zero
function DecPtr(thePointer)
{
 ArrayOfPointers[thePointer] = ArrayOfPointers[thePointer] + 1
 if (ArrayOfPointers[thePointer] == 0)
 {
   delete thePointer
 },
},

// this test makes sure delete is called on animalData data member

test()
{
 D = new dog
 data = dog.animalData
 assert( ArrayOfPointers[data] == 1 )
 delete D
 assert( ArrayOfPointers[data] == 0 )
},

If memory leaks are a big issue for you and your don't program system level code why don't you use a language with GarbageCollection?

Unfortunately, with some of those languages, memory leaks of sorts are still possible. Furthermore, creating a test for it is an interesting problem by itself.


One way to help track them down is a HeapShaker. -- TomStambaugh


Loading...