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?
Official answer and solution
- Official answer
- D
- From
- Official GATE 2021 answer key
Solution
Trace the dynamic memory allocations and pointer traversals in the C program.
In main(), the program initializes a linked list:
boxE = head = malloc(...)creates the first node withvalue = 0.- The loop
for (index = 1; index <= 3; index++)allocates 3 more nodes (with values 1, 2, and 3), linking them viaboxE->next = boxN; boxE = boxN;. - Note that after the loop, the last node's
nextpointerboxE->nextis NEVER set toNULL. Since memory frommalloccontains uninitialized indeterminate values, the last node'snextpointer holds garbage.
Next, the traversal loop executes:
for (index = 0; index <= 3; index++)
index = 0: prints node 0, setshead = head->next(node 1), prints node 1.index = 1: prints node 1, setshead = head->next(node 2), prints node 2.index = 2: prints node 2, setshead = head->next(node 3), prints node 3.index = 3: prints node 3, then executeshead = head->next(dereferencing the uninitializednextpointer of node 3), followed byhead->value.
Because the next pointer of the fourth node was never initialized to NULL or valid memory, dereferencing it causes undefined behavior, typically triggering a segmentation fault (run-time error). This matches statement D.
D
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2021 Computer Science and Information Technology - Session 2 (CS2)
- Question
- 45 of 65, printed as CS Q.35
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.