I am trying to perform a simple string manipulation (strcat) on a char array. I tried 2 approaches.
In the first case, I am allocating memory to a char* and then assigning the value through scanf() . This approach is working fine.
void fun1(char** s1) {
char temp[15] = "&Superman";
printf("inside fun1 %s %s\n",(*s1),temp);
strcat((*s1),temp);
}
int main()
{
char *str;
str = malloc(sizeof(char)*15);
scanf("%s",str);
fun1(&str);
printf("1st string %s\n",str);
return 0;
}
The O/p is as expected for this case
Batman
inside fun1 Batman &Superman
1st string Batman&Superman
In the second approach , I am assigning value to str directly in the main() without scanf().
void fun1(char** s1) {
char temp[15] = "&Superman";
printf("inside fun1 %s %s\n",(*s1),temp);
strcat((*s1),temp);
}
int main()
{
char *str;
str = malloc(sizeof(char)*15);
str = "Batman";
fun1(&str);
printf("1st string %s\n",str);
return 0;
}
In this case I am getting segmentation fault inside fun1() while strcat is getting executed.
inside fun1 Batman &Superman
Segmentation fault (core dumped)
GDB o/p from OnlineGDB
(gdb) r
Starting program: /home/a.out
inside fun1 Batman &Superman
Program received signal SIGSEGV, Segmentation fault.
__strcat_sse2_unaligned ()
at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:666
666 ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S: No such file or direc
tory.
(gdb) bt
#0 __strcat_sse2_unaligned ()
at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:666
#1 0x00000000004006a3 in fun1 (s1=0x7fffffffebd8) at main.c:9
#2 0x00000000004006e4 in main () at main.c:17
(gdb)
I am confused because the string "Batman" is able to get printed inside fun1() , but its strcat is failing eventhough I am doing the same thing for both the cases.
Thanks in advance for any help.