By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,188 Members | 834 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,188 IT Pros & Developers. It's quick & easy.

why does the below program terminate giving segmentation fault ?

P: 56
Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<malloc.h>
  3. struct node 
  4. {int a;
  5. struct node *next;
  6. };
  7. int main()
  8. {
  9. int i=0;
  10. struct node *p,*head;
  11. for( i=0;i<5;i++)
  12.  { 
  13. p=(struct node*)malloc(sizeof(struct node));
  14.  if(head==NULL)
  15. {
  16. head=p;
  17. head->next=NULL;
  18. }
  19. else
  20. {
  21. p->next=head;
  22. head=p;
  23. }
  24. }
  25. for(i=0;i<2;i++)
  26. {
  27. printf("%d  ",head->a);
  28. head=head->next;
  29. }
  30. return 0;
  31. }
Here only 2 nodes are created with some garbage value , but after the values are printed , why do I get a segmentation fault ?
Feb 28 '16 #1

✓ answered by hpmachining

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.

Share this Question
Share on Google+
3 Replies


P: 15
You are not initializing head. It is probably not NULL when the program enters the for loop.
Feb 28 '16 #2

P: 56
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 ?
Feb 29 '16 #3

P: 15
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.
Feb 29 '16 #4

Post your reply

Sign in to post your reply or Sign up for a free account.