The GATE Grind

GATE 2021 CS (CS2) – Question 45

Programming and Data Structures · Linked Lists · 2 marks · Multiple choice

Which statement about this C program is correct?

#include <stdio.h>
#include <stdlib.h>
struct Node { int value; struct Node *next; };
int main() {
 struct Node *boxE,*head,*boxN; int index=0;
 boxE=head=(struct Node*)malloc(sizeof(struct Node));
 head->value=index;
 for(index=1;index<=3;index++) {
  boxN=(struct Node*)malloc(sizeof(struct Node));
  boxE->next=boxN; boxN->value=index; boxE=boxN;
 }
 for(index=0;index<=3;index++) {
  printf("Value at index %d is %d\n",index,head->value);
  head=head->next;
  printf("Value at index %d is %d\n",index+1,head->value);
 }
}
  1. It creates a five-node list
  2. It enters an infinite loop
  3. Its missing return is a compiler error
  4. It dereferences an uninitialized pointer and may cause a runtime error

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (D) It dereferences an uninitialized pointer and may cause a runtime error

Explanation

Only four nodes, with values zero through three, are allocated. The last node’s next field is never initialized. On the final print-loop iteration, head=head->next reads that indeterminate pointer, and the following head->value dereferences it. This is undefined behaviour and can fail at runtime. Thus D; the finite loop itself is not infinite.

More Linked Lists questions

All Linked Lists questions →