The Gateway to Computer Science Excellence
+39 votes
5.2k 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 by Active (3.3k points)
edited by | 5.2k 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 .

+7

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;
}

+20
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;"
+3
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)?

3 Answers

+57 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.

by Active (3.3k points)
edited by
0
I don't understand how swap(*x,*x) produces 0. Plz explain
+51
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.
+5
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??
+7

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 ?
+5

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;
}

+13 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.

by (277 points)
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.
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.

by (63 points)

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,645 questions
56,601 answers
195,856 comments
102,231 users