Segmentation fault in C. Attempt to exchange two values using a pointer
I am getting a segmentation error when I try to swap values in two variables. My code :
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 puzzling to me is the error occurring after successfully replacing the data. What is the error? Do I need to point pointers somewhere?
source to share
The pointer int *temp;
doesn't point to anything.
So, when your program *temp=*a;
, it puts a value a
in an arbitrary block of memory.
Try this fix:
void swap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Update
Additional question:
Suppose I want to use temp as a pointer variable and not as a regular variable, is there a way to execute my program, or do I need to leave my stubbornness behind?
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);
}
source to share