Shikha thakur Shikha thakur - 2 months ago 14
C Question

Error:Segmentation fault(code dump)

I am new to data structures and started with linked list where i tried to add element at the end of the linked list but getting an error segmentation fault .
I am implementing it in C language.

I don't understand what this error means

CODE:

struct node
{
int data;
struct node *next;
};
struct node *head;
void fnInsert(int x){
if(head==NULL){
printf("head is null");
node* temp=(node*)malloc(sizeof(struct node));
temp->data=x;
temp->next=head;
head=temp;
}
else{
node* temp=head;
struct node* previousNode;
do{
temp=temp->next;
previousNode=temp;
}while(temp!=NULL);
node* temp1=(node*)malloc(sizeof(struct node));
temp1->data=x;
previousNode->next=temp1;
temp1->next=NULL;
}
};
void fnPrint(){
struct node* temp=head;
printf("list is:\n");
while(temp!=NULL){
printf("%d",temp->data);
temp=temp->next;
printf("\n");
}
}
int main(){
head=NULL;
printf("how many numbers\n");
int n,i,x;
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter the number\n");
scanf("%d",&x);
fnInsert(x);
fnPrint();
}
}


Any help would be appreciated.

Answer

The error is in these lines:

temp=temp->next;
previousNode=temp;

It should be opposite i.e

previousNode=temp;
temp=temp->next;

In your case previousNode is eventually becoming NULL and you are trying to access previousNode->next i.e Dereference a NULL pointer. So it is a segmentation fault.

Also you have used node* in many places. You should replace all of them with struct node* or you can typedef