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