GATE / CS ARCHIVE

GATE CSE 2005 / QUESTION 72

Forked values and virtual addresses

Operating Systems · Processes, Threads & System Calls · Full GATE CSE 2005 paper

GATE 2005, Q72 2 marks · MCQ
Report issue

Processes, Threads & System Calls

Question 72, GATE 2005: Code: if(fork()==0){a=a+5;printf("%d,%d\n", a,&a);}else{a=a−5;printf("%d,%d\n", a,&a);}. Parent prints u, v and child x, y. A u=x+10, v=y; B u=x+10, v≠y; C u+10=x, v=y; D u+10=x, v≠y. Address formatting is reproduced literally and requires a portability qualification.
Question 72, GATE 2005: Code: if(fork()==0){a=a+5;printf("%d,%d\n", a,&a);}else{a=a−5;printf("%d,%d\n", a,&a);}. Parent prints u, v and child x, y. A u=x+10, v=y; B u=x+10, v≠y; C u+10=x, v=y; D u+10=x, v≠y. Address formatting is reproduced literally and requires a portability qualification.
Tap to enlarge
Your answer
Answer & solution

Answer: C, under intended address-printing semantics (no official key was published)

Let a initially equal a 0. The child executes the zero-return branch and obtains x=a 0+5; the parent obtains u=a 0−5. Therefore u+10=x. fork preserves the virtual address of a, so its address has the same numeric value in each process even though the memory is logically separate: v=y. Hence C under the intended OS model. Strictly, the printed printf uses %d for &a; that variadic type mismatch is undefined behavior in ISO C, so literal portable-C output is not guaranteed. Using %p with (void *)&a expresses the intended comparison.

fork duplicates the address-space state. The child and parent modify separate copies starting from the same initial a 0: child a 0+5, parent a 0−5, hence a difference 10. Their virtual addresses retain equal numerical locations despite distinct physical memory. This supports C as the intended OS result. The actual %d address argument is type-incorrect; use %p and a void* cast to state the intended comparison in portable C.

Original paper, page 9