Home > front end >  Segmentation fault while trying to add an item at the end of a linked list
Segmentation fault while trying to add an item at the end of a linked list

Time:11-16

When I try to add an item at the end of a linked list it says segmentation fault (core dumped)

Here is the code


LinkedList :: LinkedList()
{
    head = NULL;
}

void LinkedList :: InsertItem(int data)
{
    Node *new_node;
    new_node = new Node;
    new_node -> data = data;
    new_node -> next = NULL;

    new_node -> next = head;
    head = new_node;

    cout<<"Node Added"<<"\n";
}


void LinkedList :: Display()
{
     Node *curr;
     curr = head;

    while(curr != NULL)
    {
    cout<<curr->data<<"\t";
    curr = curr -> next;
    }
}

void LinkedList :: AddLast(int data)
{
     Node *new_node = new Node;
     new_node -> data = data;
     new_node -> next = NULL;

     Node *curr = head;
     while (curr != NULL)
     { 
    curr = curr -> next;
     }

     curr -> next = new_node;

}

When I run this, it says

Segmentation fault (core dumped)

I am trying to implement this linked list without a tail node. So how should I do it?

CodePudding user response:

In the AddLast method, your iteration stops when curr == NULL. So when you attempt

curr -> next = new_node;

you get a segfault, since curr is null here.

To fix this, change your iteration to

while (curr->next != NULL)

That will ensure that the iteration stops at the last node, just like you need it to.

  • Related