search
Log In
52 votes
9.7k views

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
in Programming
edited by
9.7k views
1

How may the code generate segmentation fault depending on the arguments passed?

Any examples supporting this?

Segmentation fault occurs when a pointer pointing an invalid memory location .

10

void swap(int *px,int *py)
{
    *px = *px - *py;
    *py=*px+*py;
    *px=*py-*px;
}
int main ()
{
 
  int x=10;
  int * arr =(int *)malloc(sizeof(int));
  arr[0]=20;
  free(arr);
  swap(&x,arr);
  printf("%d %d\n",x,*arr );
  return 0;
}

28
It can cause a segmentation fault .. Ex : whenever one of px or py is a dangling pointer,our program is trying to dereference a dangling pointer .. Dereferencing a dangling pointer is nothing but accessing memory which doesnot belong to our program ... which is nothing but segmentation fault ...
0

Is adding of two pointers  allowed in C?,

 this line should throw compilation error  right?

"*py = *px + *py;"
4
We are not adding two pointers. Here we are adding two int values, which we have got by dereferencing pointers. And storing result back to the address pointed by $y$
0
we are adding the values pointed by the pointers but not the pointer variables
1

@shashank023

it does give segmentation error

it gives output 0 10

check here https://www.onlinegdb.com/online_c_compiler

1
Question says we are swapping 2 integers which means I have 2 integer variables on 2 different memory address so why we are assuming that both pointer will point on same memory address? Like passing swap(&X,&X)?
8

0
In S5:

May add or subtract integer and pointer : false statements

Reason: because pointer add or subtract for some references or swap purpose.

Only alone add pointer and subtraction of pointer is not valid.

Plz check I am right or wrong??

5 Answers

70 votes
 
Best answer

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
0
I don't understand how swap(*x,*x) produces 0. Plz explain
62
let x is d address where a no let 10 is stored.. let value of x i.e address of 10 is 1000..

now coming to the code..
void swap (int *x, int *y)  
{
    *px = *px - *py;
    *py = *px + *py;
    *px = *py - *px;
}
now put x in place y in above code..
code ll look like :
void swap (int *px, int *px) {
    *px = *px - *px;  // *px becomes 0 i.e. 10-10=0..
    *px = *px + *px; // addition of two *px i.e. 0+0=0
    *px = *px - *px;  // subtraction of two *px i.e. 0-0=0
}
0
Got it. Thanks.
6
any pointer can cause segmentation fault. It is a common fault of pointer due to illegal virtual emory access.
0
kindly elabortE the expalanation
1

"now put x in place y in above code.. "  why u r doing this plss help i m not getting ?
and also explain s5 ?
 

0
@Digvijay, How segmentation fault occurs??
9

How can segmentation fault occur with pointers

http://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault

0
S3 and S4 are contradicting statements and S4 is true because arithmetic overflow is possible. That's why S3 is false. This should be the correct reasoning. Swapping an element with itself is also a good idea to rule S3 out but it might not be sufficient because this case falls more under error handling. On the other hand, preventing arithmetic overflow is essential because it requires the whole swap method to be changed.
0
@bikram can u explain this more!
0
@digvijay sir...why you are separating p and x...i think it is complete var name.. can you explain??
1
Pointer addition is forbidden in c or c++ so how we are proceeding ,sir, please explain ?
6

Why segmentation fault happens even after successful swapping using 2 pointers

Ans here https://stackoverflow.com/questions/26113257/segmentation-fault-in-c-trying-to-swap-two-values-using-pointer

0
The program will give correct result if we are using two variable for input. The following code illustrate:-

#include<stdio.h>
int swap(int*,int*);
main()
{
    int a,b;
    printf("enter number1 and number2\n");
    scanf("%d\n%d",&a,&b);
    swap(&a,&b);
    printf("%d\n%d",a,b);
}
    int swap(int *px, int *py)
     {
        *px = *px - *py;
        *py = *px + *py;
        *px = *py - *px;
     }

 

But if we use only one variable for input,then program will not give correct result.The following code will illustrate:-

#include<stdio.h>
int swap(int*,int*);
main()
{
    int a;
    printf("enter number\n");
    scanf("%d\n%d",&a,&a);
    swap(&a,&a);
    printf("%d\n%d",a,a);
}
    int swap(int *px, int *py)
     {
        *px = *px - *py;
        *py = *px + *py;
        *px = *py - *px;
     }
0

Arjun Sir please explain how this code can be modified so as to remove segmentation fault???

0

When you call the swap function from anywhere gives correct memory location then no segmentation fault will happen.

Here segmentation happens if swap is called as call by value i.e. instead of address value are passed.

0
thanks srestha for that link
0

Why are you not focussing on the statement S3? It says "for all input pointers referring to integers stored in memory locations accessible to the process" .

It clearly says integers stored in different memory locations. Then, why are you assuming same memory location of the integers passed as arguments.

Explain?

0
Yeah. If we consider arithmetic overflow S3 is false, but notice "for all valid input pointers" in S4, so I think the context in question is pointers
0

 dangling pointers donot cause segmentation fault.

but wild pointers and dereferncing a null pointer does cause segmentation fault.

https://en.wikipedia.org/wiki/Segmentation_fault#Causes

#include <stdio.h>
#include <stdlib.h>

int main()
{
        int *p,*q,*r=NULL;
       *p=5;//wild pointer
       q=(int*)malloc(sizeof(int));
        *q=6;
        free(q);
        printf("%d",*q);// q is a dangling pointer(on running it gives an wrong output)
        printf("%d",*r);//dereferencing of null pointer.
        return 0;
}

14 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.

0
Arithmetic Overflow will not occur as the address of the variables is passed to the function and the variable which stores that integer will wrap around the integer to other side and the int get stored thereafter. So, it will work for all valid input pointers.
2 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 vote
S2:
We may get the segmentation fault if the pointer values are constant (i.e., px or py) (or) (px or py) are points to a memory location is invalid.
S4:
Swap procedure can be implemented correctly but not for all input pointers because arithmetic overflow may occur based on input values.
1
short and precise
0 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

11 votes
3 answers
1
4.2k views
Consider the following code written in a pass-by-reference language like FORTRAN and these statements about the code. subroutine swap(ix,iy) it = ix L1 : ix = iy L2 : iy = it end ia = 3 ib = 8 call swap (ia, ib+5) print *, ia, ib end S1: The compiler will generate ... and 8 S5: The program will print 13 and -2 Exactly the following set of statement(s) is correct: S1 and S2 S1 and S4 S3 S1 and S5
asked Sep 26, 2014 in Programming Rucha Shelke 4.2k views
28 votes
3 answers
2
3.8k 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 $x$ is: 3 4 6 9
asked Sep 15, 2014 in Numerical Methods gatecse 3.8k views
53 votes
7 answers
3
6k views
Which one of the choices given below would be printed when the following program is executed? #include <stdio.h> int a1[] = {6, 7, 8, 18, 34, 67}; int a2[] = {23, 56, 28, 29}; int a3[] = {-12, 27, -31}; int *x[] = {a1, a2, a3}; void print(int *a[]) { printf("%d,", a[0][2]); printf("%d,", ... } main() { print(x); } $8, -12, 7, 23, 8$ $8, 8, 7, 23, 7$ $-12, -12, 27, -31, 23$ $-12, -12, 27, -31, 56$
asked Nov 1, 2014 in Programming Ishrat Jahan 6k views
61 votes
6 answers
4
9.9k views
Which one of the choices given below would be printed when the following program is executed? #include <stdio.h> void swap (int *x, int *y) { static int *temp; temp = x; x = y; y = temp; } void printab () { static int i, a = -3, b = -6; i = 0; while (i <= 4) { if ((i++)%2 == 1) continue; a = a + i; b = ... $a = 12, b = 9$ $a = 3, b = 6$ $a = 3, b = 6$ $a = 6, b = 3$ $a = 15, b = 12$
asked Nov 1, 2014 in Programming Ishrat Jahan 9.9k views
...