Consider this C code to swap two integers and these five statements: the code
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
View worked solution
Answer: C
To determine which statements are correct, let us analyze each of them:
- S1 (False): The code is syntactically valid in C. It dereferences integer pointers and performs standard integer arithmetic, so it will compile without errors.
- S2 (True): If either
pxorpyis aNULLpointer or points to an invalid/unmapped memory address, dereferencing them (e.g.,*px) will cause a segmentation fault at runtime. - S3 (False) & S4 (True): Let us trace the code when both pointers point to the same memory location (aliasing), i.e.,
px == py. Let the value at this location be .*px = *px - *py;*py = *px + *py;*px = *py - *px;
px != py. Hence, it works for some but not all valid pointers. - S5 (False): The operations are performed on
*pxand*py, which are of typeint, not on the pointerspxandpythemselves. No pointer arithmetic is involved.
Thus, only statements S2 and S4 are correct, which corresponds to option C.
Free practice · Your answers on this page are not saved.
