Skip to content
GATEiit

GATE CSE 2021 Set 2 Q45: Bug in a linked-list program: uninitialized next pointer

Question

Consider the following 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 statements below is correct about the program?

Try it: multiple choice: exactly one correct option

Select one option
Wrong answer costs 2/3 mark in GATE.
Show answer and explanation

Answer: D (official GATE 2021 final answer key)

Concept used: malloc does not initialise memory, so the last node's next field holds garbage.

First step: Count the nodes (four: values 0 to 3) and trace the second loop: in the last iteration head moves past the fourth node.

Full step-by-step solution

Detailed working, common mistakes and linked mock tests will be available with a free GATEiit account. Log-in is coming soon.

Share this question

WhatsAppDownload image

Source: official GATE 2021 Set 2 CS question paper and final answer key, organised by IIT Bombay. Question paper · Answer key