0

How to know the segmentation faults in C? The code is below(seeing to the word limit its incomplete)

#include<stdio.h> #include<stdlib.h> struct node { int rno; struct node *next; }; void main() { int n,i,r; struct node *head; head=(struct node *)malloc(sizeof(struct node)); head=NULL; scanf("%d",&n); for(i=1;i<=n;++i) { scanf("%d",&r); if(head==NULL) { head->rno=r; head->next=NULL; } struct node *tmp; tmp=head; int f=0; while(tmp!=NULL) { if(tmp->rno==r) { f=1; break; } tmp=tmp->next; } if(f=0) { tmp->next=head; head=tmp; } if(f=1)

14th Mar 2020, 6:23 PM
Ayush Dubey
Ayush Dubey - avatar
1 Réponse
+ 2
in line head=(struct node *)malloc(sizeof(struct node)); you allocate memory for a node, but in the next line: head=NULL; you overwrite the address of allocated memory with NULL. Remove this line. segmentation fault arises in the next lines: if(head==NULL) { head->rno=r; // in this line segmentation fault arises because head is NULL head->next=NULL; } You check head on NULL and write data to head if it is NULL. But you have to do the opposite: if head is NULL you shouldn't write to it, you should allocate memory for it.
14th Mar 2020, 8:29 PM
andriy kan
andriy kan - avatar