Hello,
I'm trying to track down a memory leak using Valgrind, and was surprised by the number of "definitely lost" messages it threw at me, especially in one case where I have the following:
- A template class that manages a list of pointers (MY_LIST)
- A data object (DATA)
- A class that contains a MY_LIST and many pointers to DATA objects (CREATOR)
Some code snippets:
From my_list_class.h (some functions omitted):
Code:
template <class T>
class MY_LIST
{
public:
// Constructor
MY_LIST();
// Destructor
~MY_LIST();
// Private data accessors
int Add(T *ToAdd);
void Remove(const int &Index);
inline int GetCount(void) const { return Count; };
// Removes all objects from the list
void Clear(void);
// Operators
T *operator [](const int &Index) const;
private:
// The number of objects in this list
int Count;
// The data in the list
T **ObjectList;
};
template <class T>
MY_LIST<T>::MY_LIST()
{
// Initialize the count to zero and the pointers to NULL
Count = 0;
ObjectList = NULL;
}
template <class T>
MY_LIST<T>::~MY_LIST()
{
// Remove all of the items in this list
Clear();
}
template <class T>
void MY_LIST<T>::Clear(void)
{
// Delete all of the items in the list
int i;
for (i = 0; i < Count; i++)
{
delete ObjectList[i];
ObjectList[i] = NULL;
}
// Delete the list and set the count to zero
delete [] ObjectList;
ObjectList = NULL;
Count = 0;
return;
}
So when a MY_LIST is deleted, it deletes all of the objects that it's list of pointers point to, as well as the list itself.
The DATA object's constructor takes a pointer to a list, and it adds itself to the list in the constructor. So DATA:

ATA() looks something like this:
Code:
DATA::DATA(MY_LIST<DATA>* List)
{
List->Add(this);
}
And then I create a bunch of DATA objects in the CREATOR class, but I don't explicitly delete them. Instead, I call MY_LIST::Clear. This class looks like this:
Code:
// This class contains a private MY_LIST<DATA> object called List
CREATOR::CREATOR()
{
// Make a bunch of DATA objects
DATA* Data1 = new DATA(this);
DATA* Data2 = new DATA(this);
DATA* Data3 = new DATA(this);
// and a whole lot more...
}
CREATOR::~CREATOR()
{
List.Clear();
}
When I run Valgrind, it tells me every one of my DATA objects has leaked. I don't believe that this is correct, but I read that when Valgrind says "definitely lost" it is 100% sure.
I had CREATOR::CREATOR() print the addresses of the new objects to file, and I had MY_LIST::Clear() print the addresses of the object just before deletion to file, and the lists are identical... so this is a case where Valgrind is wrong?
Any ideas? I can post more code or a complete example if it will help.
Thanks,
Kerry