I am creating a Circular Linked List template class. I have an assignment operator that one Circular List to another. However, when I use a copy constructor to create a List and assign the original list to the copied list it generates a segmentation fault.
cout<<"cl: "<<cl<<endl;
cout<<endl<<"C
CircularList<int> cl2(cl);
cl=cl2;
I have tested this extensively using cout statements and isolated the line where the error occurs.
template <class T>
CircularList<T>& CircularList<T>::operator=(const CircularList<T>
&other)
{
this->clear();
if(other.tail==NULL)
{
tail=NULL;
return (*this);
}
Node<T> *ptr=other.tail;
tail= new Node<T>(ptr->element);
Node<T> *node=tail;
while(ptr->next!=other.tail)
{
ptr=ptr->next;
//a statement used for testing output
cout<<ptr->element<<endl;
node->next=new Node<T>(ptr->element); //segfault
node=node->next;
}
node->next=tail;
return *(this);
}
The copy constructor:
template <class T>
CircularList<T>::CircularList(const CircularList<T>& other)
{
if(other.tail==NULL)
{
tail=NULL;
return;
}
Node<T> *ptr=other.tail;
tail= new Node<T>(ptr->element);
Node<T> *node=tail;
while(ptr->next!=other.tail)
{
ptr=ptr->next;
node->next=new Node<T>(ptr->element,NULL);
node=node->next;
}
node->next=tail;
}
The code for the Node constructor:
Node(T data, Node<T>* n = 0)
{
//cout for testing
cout<<data<<endl;
element =data;
next = n;
}
When this code is run it generates the following output on an int instance of the class where the contents of the first list is [8,7,6,5,4,11,3,2,1,0]
cl: [8,7,6,5,4,11,3,2,1,0]
Copy constr:
0
8
7
6
5
4
11
3
2
1
0
8
8
7
7
6
6
5
5
4
4
11
11
3
3
2
2
1
make: *** [makefile:5: run] Segmentation fault (core dumped)
All the data is read is outputted twice, once inside the operator= function and once inside the Node's constructor, except for the last 1 where the segmentation fault occurs.
The code does not enter the Node constructors block.
I appreciate any help. Thank you!
I created a github repository with the needed files to reproduce the error: https://github.com/precious-princess-peach/Circular_linked_list_test