0

Suppose temp is a pointer to structure node. temp->next is NULL. So what will be the value of temp->next->next?

In short what is the value of NULL->next? Is it compiler dependent because I have seen different result in ubuntu and code blocks(windows)?

What will be the output of the program below?

 struct node
 {
  int data;
   struct node *next;
 };

 main()
 {
   struct node *temp,*p;
   int c=0;
   temp=(struct node *)malloc(sizeof(struct node));
   temp->data=50;
   temp->next=NULL;
   p=temp;
   if(p->next->next==NULL)//will it enter the if loop?
      c++;
   printf("%d",c);
  }
Baris Demiray
  • 1,539
  • 24
  • 35
ankush kapoor
  • 57
  • 1
  • 6
  • 2
    Should throw a segfault while evaluating the IF condition. – Michał Szydłowski Aug 12 '15 at 14:42
  • Not necessarily. Especially in Windows there is no segfaults... It's an undefined behaviour. It can blow up the Moon, for example, so please don't do this. We still need it. – Eugene Sh. Aug 12 '15 at 14:47
  • 1
    [Please do not cast the result of `malloc()`](http://stackoverflow.com/a/605858/3233393). – Quentin Aug 12 '15 at 15:01
  • I'm voting to close this question as off-topic because it's yet another 'I know it's UB but I still want SO contributors to waste time on it' – Martin James Aug 12 '15 at 16:13

2 Answers2

1

If temp->next is NULL, dereferencing it to get temp->next->next is undefined behavior. A crash is likely, but other things could happen. In principle, anything could happen.

Don't dereference null pointers.

Wyzard
  • 33,849
  • 3
  • 67
  • 87
1

NULL->next must give you a segfault.

You may want to have something like :

if(p->next != NULL && p->next->next==NULL)

or

if(p->next == NULL || p->next->next==NULL)
Vouze
  • 1,678
  • 17
  • 10