Click to See Complete Forum and Search --> : Templated linked list memory leak


Federal102
January 13th, 2004, 08:47 AM
In preparation for an interview tomorrow, I decided to try and code a simple templated linked list. I am a big fan of STL and use std::list regularly, but I have never really delved into the innards of the code.

That being said I have code that works to create the list, insert members and print them out (any comments on this gladly accepted).

I know that in the destructor (list or node) I need to free the memory and here is where I am stuck. Any ideas would be greatly appreciated.

Here is my code...


template <class T>
class myList
{
public:
myList():head(0), count(0){}
void insert(T);
void walk();
private:
struct Node
{
Node(T t):m_t(t){}
Node *next;
T m_t;
};
Node *head;
Node *current;
Node *iterator;
Node *n;
int count;
};

template <class T>
void myList<T>::insert(T ins_t)
{
if(head == 0)
{
n = new Node(ins_t);
head = n;
iterator = n;
current = n;
current->next = 0;
++count;
}
else
{
n = new Node(ins_t);
current->next = n;
current = n;
current->next = 0;
++count;
}

}

template<class T>
void myList<T>::walk()
{
int count_hold = count;
while(count)
{
cout << iterator->m_t << endl;
iterator = iterator->next;
--count;
}
iterator = head;
count = count_hold;
}

int main(int argc, char* argv[])
{
myList<string> v;
v.insert("Hello");
v.insert("World");

v.walk();

return 0;
}

mwilliamson
January 13th, 2004, 07:54 PM
You are not freeing any memory anywhere. When your list is destructed you need to delete all the nodes in it.

its pretty simple:

while( head != null )
{
Node* old = head;
head = head->next;
delete old;
}

CornedBee
January 14th, 2004, 02:28 PM
You need to initialize all pointers to 0 in the constructor, too.

Federal102
January 14th, 2004, 05:59 PM
Thanks