I was trying out a sample program to understand about the generic swap function.
/* A simple generic swap function */
#include<stdio.h>
#include<string.h>
void swap(void* xp,void* yp,int size){
//void temp = *xp; // we cant declare a variable as void , as we need to konw to de-reference as its not specifying any size info
// Hence used the smallest type info - char
char buffer[size];
memcpy(buffer,xp,size);
memcpy(xp,yp,size);
memcpy(yp,buffer,size);
}
int main(){
int a = 10;
int b = 20;
double d=1.34;
double e=2.34;
char* s = "Hello";
char* t = "World";
printf("\n a : %s b : %s \n",s,t);
swap(s,t,sizeof(char*));
printf("\n a : %s b : %s \n",s,t);
return 0;
}
I got a segmentation fault when I ran the above program with the function call as swap(s,t,sizeof(char*)). But if I run it with swap(&s,&t,sizeof(char*)), I don't get any segmentation fault.
gdb o/p:
Breakpoint 2, swap (xp=0x4007ac, yp=0x4007b2, size=8) at swap_generic1.c:5
5 void swap(void* xp,void* yp,int size){
(gdb) s
8 char buffer[size];
(gdb) s
9 memcpy(buffer,xp,size);
(gdb) s
10 memcpy(xp,yp,size);
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b64fe4 in ?? () from /lib/x86_64-linux-gnu/libc.so.6
what might be the cause of the problem. Is that when passed as s and t, the argument is assigned with the address of the strings "Hello" and "World" respectively, and the pointer increments goes sto some other location to fetch the values.