Skip to content
Official PYQ · 2021

GATE CS 2021 Set 2 Q35 — Programming in C

Explain with AI
Consider the following ANSI C\text{ANSI C} program:
#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); } }

Which one of the following statements below is correct about the program?

Choose one option
View worked solution

Answer: D

Let's trace the execution of the program step-by-step:

1. Linked List Creation:

  • Initially, a node is allocated and pointed to by head and boxE. Its value is set to 0.
  • The for loop runs for index = 1, 2, 3, allocating three more nodes (with values 1, 2, and 3) and linking them.
  • At the end of this loop, the last node (value 3) is pointed to by boxE. However, boxE->next is never initialized to NULL. Since memory is allocated via malloc, boxE->next contains garbage/uninitialized data.

2. Printing Loop:

The second loop runs for index = 0, 1, 2, 3:

  • For index = 0, 1, 2, the program successfully prints the values of the nodes (0, 1, 2, 3) as head advances from Node 0 to Node 3.
  • For index = 3:
    • The first printf prints the value of Node 3 (which is 3).
    • The statement head = head->next; assigns the uninitialized next pointer of Node 3 to head.
    • The second printf attempts to dereference this uninitialized pointer via head->value.

Dereferencing an uninitialized pointer leads to undefined behavior and typically results in a segmentation fault (run-time error).

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions