Consider this C code to swap two integers and these five statements: void swap(int *px, int *py) { *px = *px - *py; *py = *px + *py; *px = *py - *px; } S1: will generate a compilation error S2: may generate a segmentation fault at runtime depending on the arguments passed S3: correctly implements the swap procedure for all input pointers referring to integers stored in memory locations accessible to the process S4: implements the swap procedure correctly for some but not all valid input pointers S5: may add or subtract integers and pointers A. S1 B. S2 and S3 C. S2 and S4 D. S2 and S5

GATE 2006 · Programming and Data Structures · Pointers · medium

Answer: C. S2 and S4

  1. Check S1 — compilation error: The code uses standard C pointer dereferencing and integer arithmetic. There is no syntax error or type mismatch. S1 is FALSE.
  2. Check S2 — segmentation fault possibility: If px or py is NULL (or any invalid pointer), dereferencing it with `*px` or `*py` causes a segmentation fault at runtime. The function does no NULL check. S2 is TRUE.
  3. Check S3 and S4 — correctness for aliased inputs: Case 1 (px != py): Let *px=a, *py=b. After line 1: *px=a-b. After line 2: *py=(a-b)+b=a. After line 3: *px=a-(a-b)=b. Swap works. Case 2 (px == py, same memory cell): Let *px=*py=a. Line 1: *px=a-a=0. Line 2: *py=0+0=0. Line 3: *px=0-0=0. Value destroyed — swap fails. So S3 (correct for ALL) is FALSE; S4 (correct for some but not all) is TRUE.
  4. Check S5 — mixing integers and pointers: All arithmetic operates on `*px` and `*py` which are integers (int). No pointer arithmetic is performed. S5 is FALSE.
  5. Select the answer: True statements: S2 (segfault possible) and S4 (works for some but not all). This matches option C.