c - 在 malloc 之后直接为 char 指针赋值会导致分段错误
问题描述
我正在尝试对 char 数组执行简单的字符串操作(strcat)。我尝试了 2 种方法。
在第一种情况下,我将内存分配给 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 失败了,尽管我对这两种情况都做了同样的事情。
提前感谢您的帮助。
解决方案
当你这样做
str = "Batman";`
str
不再指向 malloc 的内存。它指向字符串文字“batman”。所以你不能连接另一个字符串。
看到这一点的一种方法是添加一些简单的打印 - 尝试:
char *str;
str = malloc(sizeof(char)*15);
printf("%p\n", (void*)str);
str = "Batman"; // str now points to a different location
printf("%p\n", (void*)str);
改用strcpy
:
str = malloc(sizeof(char)*15);
strcpy(str, "Batman");
注意:您为“Batman”和“&Superman”的串联分配的内存太少。第一个是 6 个字符,第二个是 9 个字符,所以你需要 6+9+1 = 16 个字符。最后一个 +1 用于保存字符串终止字符,即\0
. 所以除了使用之外strcpy
,你还需要分配 16 个字符。
顺便提一句:
您不需要将地址传递
str
给函数,因为函数从不执行任何赋值,例如*s1 = ... something...
Just passstr
sizeof(char)
总是 1 所以你不需要写它。
推荐阅读
- c++ - 合并排序错误 C++
- c++ - CLion MakeFile 构建失败
- docker-for-windows - 在 Docker-compose 中使用现有的文件共享/卷和 Docker for Windows WSL2
- r - 更改 .Rprofile 中的图形显示选项
- vb.net - 双列表成员之间的减法
- paypal - 贝宝订阅 API 集成。我什么时候需要创建产品?
- c++ - 接受任何大小的 char 的 std::array 作为非类型模板参数
- python-3.x - 获取顶点和连接到它的顶点的详细信息
- list - 创建我自己的模块和类型没有按预期工作
- python - python字典异步安全吗?