So I am using linklist to make a list of names and i have been given a task to use both this pointer as well as destructor.The code written by me is
#include <iostream>
using namespace std;
class node
{
char name[50];
node*next;
public:
friend class sll;
};
class sll:public node
{
public:
node*head;
node*last;
int*k;
friend class node;
sll()
{
head=NULL;
last=NULL;
}
~sll()
{
node*temp2;
node*temp;
temp = head;
while(temp!=NULL)
{
temp2 = temp->next;
delete(temp);
temp = temp2;
}
}
void input()
{
node*temp;
temp = new node;
cout<<"Enter Name"<<endl;
cin>>temp->name;
if(head==NULL)
{
head = temp;
last = temp;
}
else
{
last->next = temp;
last = temp;
}
}
void output()
{
node*temp;
temp = head;
while(temp!=NULL)
{
cout<<temp->name<<" ";
temp = temp->next;
}
}
sll &get()
{
return *this;
}
};
int main()
{
sll obj,obj1;
obj.input();
obj1 = obj.get();
obj1.output();
return 0;
}
The error i am getting is double free or corruption
Now what i think is that i am getting this particular error because obj1 = obj.get()
copies the address of obj in obj1. Hence when i try to delete the linklist ,it gives me error because i am freeing in twice(as i have two objects of class sll).But if it is so, why am i not getting any error if i replace the destructor block with
~sll()
{
delete(k);
}
Can Anyone help me to figure it out?