CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jun 2002
    Location
    Boston, MA
    Posts
    139

    Templated linked list memory leak

    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...

    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;
    }

  2. #2
    Join Date
    Dec 2001
    Location
    Ontario, Canada
    Posts
    2,236
    You are not freeing any memory anywhere. When your list is destructed you need to delete all the nodes in it.

    its pretty simple:

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

  3. #3
    Join Date
    Nov 2003
    Location
    Vienna, Austria
    Posts
    212
    You need to initialize all pointers to 0 in the constructor, too.
    All the buzzt
    CornedBee

  4. #4
    Join Date
    Jun 2002
    Location
    Boston, MA
    Posts
    139
    Thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured