I encountered this problem while solving a practice test
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.
Which of the above statement(s) is/are correct?
I think S2 and S3. Could anyone please confirm
I don’t believe S3 holds, since if you call it with
px == py, it will just set the integer to 0 in the first line (*px = *px - *pyis then equivalent to*px = *px - *pxwhich obviously stores a 0 in*px). With all input data set to 0, it’s unable to recover and re-generate the value.