c - Segmentation fault while trying to insert node into a linked list -


i started learning c programming few days ago through book, programming in c, , have prior knowledge of java. inserting node linked list easy in java, thought if same in c. so, came program,

#include "node.h"  void insertentry(struct node* root, struct node* after) {     struct node* first = root;     while(first != (struct node*) 0)     {         if(first->value == after->value)         {             struct node ins;             ins.value = 3456;             ins.next = first->next;             first->next = &ins;         }         first = first->next;     } }  int main(void) {     struct node n1, n2, n3;     struct node* list_pointer = &n1;      n1.value = 100;     n1.next = &n2;      n2.value = 200;     n2.next = &n3;      n3.value = 300;     n3.next = (struct node*) 0;      void insertentry(struct node* root, struct node* after);      while (list_pointer != (struct node*) 0)     {         printf("%i\n", list_pointer->value);         list_pointer = list_pointer->next;     }     printf("\n");      list_pointer = &n1;      insertentry(list_pointer, &n2);      while (list_pointer != (struct node*) 0)     {         printf("%i\n", list_pointer->value);         list_pointer = list_pointer->next;     }      return 0; } 

node.h

#include <stdio.h>  struct node {     int value;     struct node* next; }; 

basically, program takes pointer first element of linked list , pointer element after inserted, , inserts new node after node.

but when run this, program crashes , cannot find or why error occurs. looked on code in java , tried implement same in c.

thank you.

here's problem:

    {         struct node ins;  // create object in stack         ins.value = 3456;         ins.next = first->next;         first->next = &ins;   // reference object     }  // object popped out of stack , ceases exist     // access first->next past block may cause segfault 

in order avoid this, create ins malloc(), beware: isn't java , have keep track of objects allocated in heap yourself.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -