Similar questions 3 more →
Pointers & Memory


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.