Reputation: 5
I'm trying to create a deep copy constructor of a singly linked list class. It copies the head of the new list and appends elements to the end of it (by calling an append) function.
The full code is available here: https://onlinegdb.com/Hke0ev8bG
Can anyone point out where I'm going wrong? Much appreciated!
class LinkedList
{
class Node
{
public:
int *data;
Node *next;
Node() {
data = NULL;
next = NULL;
}
Node(int *d) {
data = d;
next = NULL;
}
};
private:
Node *head;
int itemCount;
public:
LinkedList() {
head = NULL;
itemCount = 0;
}
//COPY CONSTRUCTOR
LinkedList(LinkedList ©)
{
Node *temp = copy.head;
while (temp != NULL)
{
append(temp->data);
temp = temp->next;
}
}
//ADD TO THE END OF A LIST
void append(int *d) {
Node *tail = new Node;
tail->data = d;
tail->next = NULL;
if (head == NULL) {
head = tail;
}
else {
Node *temp = new Node;
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = tail;
}
itemCount++;
}
The problem is that the program runs into a "Segmentation fault" at the copy constructor part.
Upvotes: 0
Views: 595
Reputation: 6393
You forgot to initialize LinkedList::head
and LinkedList::itemCount
in the copy constructor. The initialization performed in the regular constructor only applies when the regular constructor is actually used.
As a result, LinkedList::append
sees random garbage when checking the head
pointer, assumes it's valid and then causes a seg fault when using that invalid pointer.
Upvotes: 3