I am getting a segmentation fault while trying to attempt swapping values in two variables. My code is :
void swap(int *a,int *b){
int *temp;
*temp=*a;
*a=*b;
*b=*temp;
}
int main(){
int i=1,j=0;
printf("Before %d,%d\n",i,j);
swap(&i,&j);
printf("After %d,%d\n",i,j);
return 0;
}
I am getting the following error:
Before 1,0
After 0,1
Segmentation fault (core dumped)
What looks mysterious to me is the error is being produced after the values have been swapped successfully. What is the bug? Do I need to typecast the pointers anywhere?
Your pointer int *temp;
points on nothing.
So, when your program does *temp=*a;
, it puts value of a
into random memory block.
Try this fix:
void swap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Updated:
Additional question:
Suppose I want to use temp as a pointer variable and not as a regular variable, is there any way to get my program executed or I need to leave my stubbornness?
Answer: you can try this:
void swap(int *a,int *b){
int *temp;
temp = malloc(sizeof(int));
if (temp == NULL)
return;
*temp=*a;
*a=*b;
*b=*temp;
free(temp);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments