user966892
user966892

Reputation:

C code to swap two integers by passing pointers to a swap function

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

Upvotes: 2

Views: 1455

Answers (4)

duedl0r
duedl0r

Reputation: 9424

  • S2 is true.
  • S4 is true, because S3 is false due to aliasing problem.
  • rest is false

Without aliasing problem it really would swap values:

px                                              | py
-------------------------------------------------------------------------------
px := px-py                                 |
                                                  | py := px+py => px-py+py = px
px := py-px => px-(px-py) = py   |

Upvotes: 0

Vinicius Kamakura
Vinicius Kamakura

Reputation: 7778

S1: False, the code will compile
S2: True, never checks for NULL
S3: False, as unwind pointed out, if px == py it would fail
S4: True for the case cited above
S5: False, never subtracts any pointers

edit: i was wrong saying the code doesnt swap :)

Upvotes: 2

Daniel Fischer
Daniel Fischer

Reputation: 183858

You are very close, but know that (signed) integer overflow yields undefined behaviour. That may slightly alter your answers.

Upvotes: 1

unwind
unwind

Reputation: 399753

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 - *py is then equivalent to *px = *px - *px which obviously stores a 0 in *px). With all input data set to 0, it's unable to recover and re-generate the value.

Upvotes: 3

Related Questions