Ven*_*cat 0 c string segmentation-fault string-literals strcpy
据我所知,字符串文字存储在只读内存中,并在运行时修改它导致分段错误,但我的下面的代码编译没有分段错误.
#include <string.h>
#include <stdio.h>
int main() {
char* scr = "hello";
strcpy(scr,scr);
printf("%s\n",scr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:你好
同样的事情,如果我试图将源字符串复制到不同的目标字符串文字,它会抛出一个分段错误
#include <string.h>
#include <stdio.h>
int main() {
char* scr = "hello";
char* dst = "hello";
strcpy(dst,scr);
printf("%s\n",dst);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:分段故障(核心转储)
根据K&R的书,strcpy()的实现类似于下面的内容
void strcpy(char *s, char *t)
{
while ((*s = *t) != '\0') {
s++;
t++;
}
}
Run Code Online (Sandbox Code Playgroud)
如果是这样,我应该在两种情况下都有分段错误.
编译细节:
gcc版本7.3.0(Ubuntu 7.3.0-27ubuntu1~18.04)