Search code examples
csegmentation-faultcoredump

I got this code to inset an element at the end of the list.Segmentation fault


Hey guys i code this code for inserting an element at the end of the list

#include <stdio.h>
#include <stdlib.h>
struct node{
    int data;
   struct node *link;
};
struct node*head;
void insert(int x){
    struct node*temp=(node*)malloc(sizeof(struct node));
   temp->data=x;
   temp->link=NULL;
   struct node*temp1=head;
   while(temp1->link!=NULL)
       temp1=temp1->link;
   temp1->link=temp;
};
void display(){
    struct node*temp=head;
    printf("LIst is:");
    while(temp!=NULL){
        printf("%d",temp->data);
        temp=temp->link;
    }
    printf("\n");
};
int main()
{ head=NULL;
    int n,i,x;
    printf("Enter the number of elements:");
    scanf("%d",&n);
    for(i=0;i<n;i++){
        printf("Enter the elements:");
        scanf("%d",&x);
        insert(x);
        display();
    }

}

Every time i compile it.It shows

Segmentation fault core dumped 

please help i don't know what wrong am i accessing memory that “does not belong to me.


Solution

  • You assign head to temp1

    struct node*temp1=head;
    

    And at this moment head is NULL

    then you dereference temp1 (NULL)

    while(temp1->link!=NULL)
    

    That's why you get a segfault.