GATE / CS ARCHIVE

GATE CSE 2021 SET 2 / QUESTION 35

GATE CSE 2021 Set 2 Q35

Programming in C · Pointers & Memory · Full GATE CSE 2021 Set 2 paper

GATE 2021 Set 2, Q35 2 marks · MCQ
Report issue

Pointers & Memory

Question 35, GATE 2021: C Node has int value; Node *next. Allocate head=boxE, set value=0. For index=1..3 allocate boxN, set boxE->next=boxN, boxN->value=index, boxE=boxN. Then for index=0..3 print head->value, assign head=head->next, and print head->value again. No final next initialization occurs. A five nodes created; B infinite loop; C missing return causes compile error; D uninitialized pointer dereferenced, possibly runtime error.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

The initial allocation plus three loop allocations create four nodes with values 0, 1, 2, 3. The final node’s next field is never initialized. The second loop advances head and dereferences it again each iteration; on the fourth iteration it reads that uninitialized next pointer and uses it for head->value. This is undefined behavior and may cause a runtime error, D. The loops themselves have bounded iteration counts.

Before the second loop, the chain is 0→1→2→3→uninitialized. The first three iterations safely advance to nodes 1,2,3 if allocation succeeds. The last iteration prints 3, then follows the indeterminate pointer and dereferences it. Initializing next to NULL alone would still leave the unconditional extra dereference invalid; correct traversal tests the pointer before using it. Allocation failure is another issue, not needed for the intended diagnosis.

Original paper, page 75 · Answer key