GATE / CS ARCHIVE

GATE CSE 2001 / QUESTION 2.18

Pointer lifetime and initialization errors

Programming in C · Pointers & Memory · Full GATE CSE 2001 paper

GATE 2001, Q2.18 2 marks · MCQ
Report issue

Pointers & Memory

Question 2.18, GATE 2001: Three C functions return int pointers. P1 returns &x for automatic local int x=10. P2 declares uninitialized int *px, stores *px=10, then returns px. P3 allocates sizeof(int) with malloc, stores 10 through the pointer, and returns it. Which have pointer problems: only P3; P1/P3; P1/P2; all three? Distinguish the intended successful-allocation model from failure handling.
Question 2.18, GATE 2001: Three C functions return int pointers. P1 returns &x for automatic local int x=10. P2 declares uninitialized int *px, stores *px=10, then returns px. P3 allocates sizeof(int) with malloc, stores 10 through the pointer, and returns it. Which have pointer problems: only P3; P1/P3; P1/P2; all three? Distinguish the intended successful-allocation model from failure handling.
Tap to enlarge
Your answer
Answer & solution

Answer: C under successful allocation for P3 (no official key was published)

Step 1: P1 returns the address of an automatic local int. Its lifetime ends when the function returns, so the returned pointer cannot be used to access that former object.

Step 2: P2 declares an uninitialized pointer and immediately writes through it. No valid target object has been established, causing undefined behavior.

Step 3: P3 allocates sizeof(int), writes 10 into the allocated object, and returns its pointer. Successfully allocated storage remains alive until freed, even after the function returns. Thus the intended contrast is P1 and P2, C.

Practical qualification: P3 must check malloc’s result before dereferencing it and the caller must eventually free it. If allocation fails, the unchecked P3 is also erroneous; appropriate declarations/headers are assumed.

Original paper, page 6