why does the below program terminate giving segmentation fault ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • radha gogia
    New Member
    • Feb 2015
    • 56

    why does the below program terminate giving segmentation fault ?

    Code:
    #include<stdio.h>
    #include<malloc.h>
    struct node 
    {int a;
    struct node *next;
    };
    int main()
    {
    int i=0;
    struct node *p,*head;
    for( i=0;i<5;i++)
     { 
    p=(struct node*)malloc(sizeof(struct node));
     if(head==NULL)
    {
    head=p;
    head->next=NULL;
    }
    else
    {
    p->next=head;
    head=p;
    }
    }
    for(i=0;i<2;i++)
    {
    printf("%d  ",head->a);
    head=head->next;
    }
    return 0;
    }
    Here only 2 nodes are created with some garbage value , but after the values are printed , why do I get a segmentation fault ?
  • hpmachining
    New Member
    • Oct 2015
    • 15

    #2
    You are not initializing head. It is probably not NULL when the program enters the for loop.

    Comment

    • radha gogia
      New Member
      • Feb 2015
      • 56

      #3
      So what is the issue then , it will directly be going to else part and continue with p->next=head and head=p , what's the issue here ?

      Comment

      • hpmachining
        New Member
        • Oct 2015
        • 15

        #4
        If head is some garbage value, I am thinking the p->next=head line will be assigning an invalid address to p->next. I could be wrong, but you could try setting head to NULL before entering the loop to see if it fixes it. I tried your program with Visual Studio and GCC. VS wouldn't compile without initializing and GCC didn't give me the seg fault, so I can't say for sure if that is the problem.

        Comment

        Working...