edited by
20,771 views
78 votes
78 votes

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

  1. S1
  2. S2 and S3
  3. S2 and S4
  4. S2 and S5
edited by

4 Answers

Best answer
90 votes
90 votes

S1 is false.

S2 is true, depending on the argument passed it may generate segmentation fault.

S3 is false because implementation is having some problem. Let $x=3$ and I want to implement $SWAP[x,x]$. Now ans would be $0$ but that must be $x$. Problem is because we are not checking whether both pointer are pointing the same address or different So, S4 is true.

S5 is obviously false so, option (C) is right.

edited by
21 votes
21 votes

Option C

S1:FALSE-It will generate runtime error(If occur),not compile time

S2:TRUE- May generate segmentation fault if value at pointers px or py is constant or px (or) py points to a memory location that is invalid (or) px or py may contain NULL. 
S4:TRUE- May not work for all inputs as arithmetic overflow can occur.

8 votes
8 votes

S1: False 

S2:True

if we pass address NULL to px and NULL to py then there can be segmentation fault at runtime 

S3: False 

reason1:If we give address of single integer to both px and py

e.g

x=10;

swap(&x,&x) i.e.

px=&x

py=&x

now 

$*px = *px - *py;$

it will make x=0

$*py = *px + *py;$

x will still remain 0

$*px = *py - *px;$
x will still remain 0

so no swapping occurred

reason2:if we have very large two integer e.g

x=-32,768(max negative no. that int datatype can hold)

y=32,767(max positive no. that int datatype can hold)

now on calling swap(&x,&y)

*px = *px - *py
this line does $-32,768-32,768=65535$

int cannot hold 65535 so overflow occurred and it won’t swap the  numbers

S4:True

S5:False

Answer(c)

1 votes
1 votes

Option B is correct.

S1: False

S2: True. Dereferncing uninitialized pointer may generate segmentation fault, depend on argument passed.

S3: True. correctly implements swapping for each input. It can swap same integer value from different 'memory locations' (given in stmt)

S4: False.

S5: False.

Answer:

Related questions

30 votes
30 votes
3 answers
2
gatecse asked Sep 15, 2014
11,297 views
Consider the polynomial $p(x) = a_0 + a_1x + a_2x^2 + a_3x^3$ , where $a_i \neq 0$, $\forall i$. The minimum number of multiplications needed to evaluate $p$ on an input ...
62 votes
62 votes
11 answers
4