GATE / CS ARCHIVE

GATE CSE 2006 / QUESTION 57

Arithmetic swap with pointer aliasing

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

GATE 2006, Q57 2 marks · MCQ
Report issue

Pointers & Memory

Question 57, GATE 2006: C code:
void swap(int *px,int *py) {
 *px=*px-*py;
 *py=*px+*py;
 *px=*py-*px;
}
Statements: S1 compilation error; S2 may cause a segmentation fault for some arguments; S3 correctly swaps for all pointers to accessible integers; S4 correctly swaps for some but not all valid input pointers; S5 may add/subtract integers and pointers. Which statements are intended to be true?
Options:
(A) S1
(B) S2 and S3
(C) S2 and S4
(D) S2 and S5
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. The code uses *px=*px−*py; *py=*px+*py; *px=*py−*px. For distinct valid integer objects and arithmetic without signed overflow, initial values x,y become x−y,y then x−y,x then y,x, correctly swapping.

2. If px=py, the first assignment zeroes the shared object and the result is not a swap unless it was zero. Invalid pointers may cause a segmentation fault.

3. Thus S2 and S4 are the intended statements: C. No pointer arithmetic occurs, and there is no intrinsic compilation error.

4. Signed overflow is an additional undefined-behavior limitation even with distinct accessible objects.

5. Teaching check: Aliasing is decisive: if px and py point to the same nonzero integer, the first subtraction writes zero and destroys the original value. With distinct valid cells the algebraic swap works only when each intermediate signed operation is representable. Dereferencing an invalid pointer is a further separate risk.

Original paper, page 8