eri*_*ork 3 c segmentation-fault
为什么会发生以下情况:
char s[2] = "a";
strcpy(s,"b");
printf("%s",s);
Run Code Online (Sandbox Code Playgroud)
- >执行没有问题
char *s = "a";
strcpy(s,"b");
printf("%s",s);
Run Code Online (Sandbox Code Playgroud)
- > segfault
不应该第二个变体也分配2个字节的内存s,因此有足够的内存来复制"b"吗?
Gra*_*and 12
char *s = "a";
Run Code Online (Sandbox Code Playgroud)
指针s指向字符串文字"a".尝试写入此函数具有未定义的行为,因为在许多系统中,字符串文字存在于程序的只读部分中.
字符串文字属于类型char[N]而不是const char[N]使其更清晰,这是历史事故.
第二个变体不应该为s分配2个字节的内存,因此有足够的内存来复制"b"吗?
不,char *s指向包含字符串的静态内存地址"a"(写入该位置会导致您遇到的段错误),而char s[2];本身则提供字符串所需的空间.
如果要手动为字符串分配空间,可以使用动态分配:
char *s = strdup("a"); /* or malloc(sizeof(char)*2); */
strcpy(s,"b");
printf("%s",s); /* should work fine */
Run Code Online (Sandbox Code Playgroud)
之后不要忘记free()你的字符串.