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);
  }
4
  • 2
    Should throw a segfault while evaluating the IF condition. Commented Aug 12, 2015 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. Commented Aug 12, 2015 at 14:47
  • 1
    Please do not cast the result of malloc(). Commented Aug 12, 2015 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' Commented Aug 12, 2015 at 16:13

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.