Help me with the linked list insertion at anywhere

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));


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;



node head = NULL;

int i=0, position, data;

printf("1. Insert data\n2.Exit\n ");



printf("Choice: ");


printf("Enter position: ");


printf("Enter 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? */


A few things that I noticed :

  1. printf("%d\n", head->data); crashes because you are not updating the head during insert. It is not inaccessible, but null. You need to pass variable head by reference to insert, so change its signature to void insert(node& head, int i, int pos)

  2. You need to handle the casees where pos > number of elements in the linked list. this should fix second call crash in insert.

  3. You should allocate the node using malloc(sizeof(node_type));

1 Like
  • please don’t paste whole code here just

  • paste a link of some online compiler which contain your code that is easy to run and see all the debug stuff…

  • online compiler …ideone,codepad,pastebin and many more…

But head itself is a pointer.
typedef struct node_type *node;
node head;
So, head is a pointer of type struct node_type. So, when passing the head as an argument, any changes made inside the function, shouldn’t it cause a change in the original variable as well?

Thank you for your advice. I didn’t know that.

yes head is a pointer, but you need to pass its address to modify it. you can pass it as node* head or node& head for the same.