Thread: Linked List

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    5

    Linked List

    there is some memory leakage problem probably in the destructor....can somone help me plzzz..
    Code:
    #include<iostream>
    
    using namespace std;
    
    struct Node
    {
    	int data;
    	Node *next;
    };
    
    class linklist
    {
    private:
    	Node *head;
    
    public:
    	linklist(){head=NULL;}
    	void add(int);
    	void remove();
    	void print();
    	~linklist();
    };
    
    void linklist::add(int d)
    {
    	Node *current,*prev;
    	Node *temp=new Node;
    	temp->data=d;
    
    	for(current=head;current!=NULL && current->data<d;current=current->next)
    	{
    		prev=current;
    	}
    
    	temp->next=current;
    	if(current==head)
    		head=temp;
    	else
    		prev->next=temp;
    }
    void linklist:: print()
    {
    	Node *current;
    	for(current=head;current!=NULL;current=current->next)
    		cout<<current->data<<endl;
    	if(head==NULL)
    		cout<<"empty list"<<endl;
    }
    linklist::~linklist()
    {
    	Node *curr;
    	for(curr=head;curr!=NULL;curr=curr->next)
     		delete curr;
    	
    
    }
    
    int main()
    {
    	linklist link;
    	link.add(2);
    	link.add(1);
    	link.print();
    	return 0;
    }

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    linklist::~linklist()
    {
        Node *curr;
        for(curr=head;curr!=NULL;curr=curr->next)
            delete curr;
    }
    Yes, I'd say that's a problem. How can you delete curr and then do the curr=curr->next operation? You need another temp pointer in the mix to save the node you are about to delete, then you update curr before deleting the temp node.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ Linked list program need help !!!
    By dcoll025 in forum C++ Programming
    Replies: 1
    Last Post: 04-20-2009, 10:03 AM
  2. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  3. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 10:01 AM
  4. Template Class for Linked List
    By pecymanski in forum C++ Programming
    Replies: 2
    Last Post: 12-04-2001, 09:07 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM