struct node_type
{
int data;
struct node_type *next;
};
typedef struct node_type *node;
node create() //to create a new node
{
node temp = malloc(sizeof(node));
if(temp==NULL)
exit(EXIT_FAILURE);
temp->next = NULL;
return temp;
}
void insert(node head, int i, int pos) //Insert a node at anywhere
{
node temp = head;
node a = create();
if(pos == 1) //Insertion at the beginning
{
a->data = i;
a->next = head;
head = a;
return ;
}
while((–pos)>1) //Pointing to the position just before, where the new node has to be inserted
temp = temp->next;
a->data = i;
a->next = temp->next;
temp->next = a;
}
main()
{
node head = NULL;
int i=0, position, data;
printf("1. Insert data\n2.Exit\n ");
while(i!=2)
{
printf("Choice: ");
scanf("%d",&i);
printf("Enter position: ");
scanf("%d",&position);
printf("Enter data: ");
scanf("%d",&data);
insert(head,data,position); /During the first call, it runs perfectly. During the 2nd call,
Segmentation fault error is shown. Why is it happening?What's wrong with the code?
/
printf("%d\n", head->data); /*Not related to the program, used for debugging. But, the program crashes while executing this statement. After all, head pointer is local to main. Why is it inaccessible? */
}
}