【发布时间】:2020-05-12 13:17:36
【问题描述】:
我正在尝试对 char 数组执行简单的字符串操作 (strcat)。我尝试了两种方法。
在第一种情况下,我将内存分配给 char*,然后通过 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);
scanf("%s",str);
fun1(&str);
printf("1st string %s\n",str);
return 0;
}
这个案例的 O/p 符合预期
Batman
inside fun1 Batman &Superman
1st string Batman&Superman
在第二种方法中,我直接在 main() 中为 str 赋值,而不使用 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;
}
在这种情况下,我在执行 strcat 时在 fun1() 中遇到分段错误。
inside fun1 Batman &Superman
Segmentation fault (core dumped)
来自OnlineGDB的GDB o/p
(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)
我很困惑,因为字符串 "Batman" 能够在 fun1() 中打印,但它的 strcat 失败了,尽管我对这两种情况都做了同样的事情。
提前感谢您的帮助。
【问题讨论】:
-
此外,您的第一个代码会调用未定义的行为,因为您只分配 15 个字节,而您需要 16 个字节来保存包含 nul 终止符的结果字符串。
-
为什么要在第二个代码中分配内存?您立即丢弃地址导致内存泄漏。
-
@Gerhardh 是的,我的错。我只是在尝试一些东西。
标签: c string pointers segmentation-fault malloc