Home > Back-end >  Getting a segmentation error in this. Tried to debug so much to no avail. where am I getting it wron
Getting a segmentation error in this. Tried to debug so much to no avail. where am I getting it wron

Time:12-22

#include <stdlib.h>
#include <stdio.h>

struct Node{

    int data;
    Node* next;

};

Node* head;

void insert(int num){

    Node* temp = new Node;
    temp -> data = num;
    temp -> next = NULL;

    Node* temp1 = head;

    while(temp1 -> next != NULL){

        temp1 = temp1 -> next;

    }

    temp1 -> next = temp ;

}

void print(){

    Node* temp2;
    temp2 = head;

    printf("Current list is:");
    while(temp2->next != NULL){

        printf("  %d", temp2 -> data);
        temp2 = temp2 -> next;
        printf("\n");

    }

}

int main()
{
    
    head = NULL;

    insert(1);
    insert(2);
    insert(3);
    insert(4);
    insert(5);
    insert(6);
    insert(7);
    insert(8);

    print();

    return 0;
}

This is supposedly programmed to insert an element at end of a linked list. however compiler showing segmentation fault without any useful traceback. tried finding; but couldn't get where is this getting wrong. also used a debugger but it isn't helping as well.

CodePudding user response:

In insert() the step Node* temp1 = head; you're assigning a nullptr to temp1, so therefore you cannot access its ->next element

In this case head = new Node(); in main() would fix your issue. Ignoring practices.

CodePudding user response:

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

Consider what happens the very first time you call insert. The global head is still NULL, so temp1 is NULL, so accessing temp1->next is invalid.

You need to consider the case where head is NULL and assign the new node there.

That's of course aside from the general bad practice here (global variable, leaking memory all over the place, no encapsulation, no destructors, using NULL instead of nullptr, C headers, ...)

CodePudding user response:

It looks like you never initialize head, meaning its value is always NULL. Then when you try to insert the first value into the linked list you try to access next on NULL.

Also, it looks like your print() function will never print the last element, because the last element's next is always NULL, therefore the condition in the while statement (temp2->next != NULL) is always false for the last element in the list.

  • Related