Reputation: 397
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?
Upvotes: 3
Views: 1980
Reputation: 4689
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);
}
Upvotes: 11
Reputation: 4971
Use this swap function :-
void swap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Upvotes: 1
Reputation: 1
Your swap
function is wrong. It should be
void swap(int *a,int *b){
int temp = *a;
*a= *b;
*b= temp;
}
Upvotes: 3