C strcpy()复制字符串文字而没有分段错误

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)

Sou*_*osh 7

字符串文字存储在只读内存中,在运行时修改它会导致分段错误,

不,你错了.它调用未定义的行为,并且分段错误是UB 的许多可能影响之一.

引用C11,章节§6.4.5/ P7,字符串文字

[...]如果程序试图修改这样的数组,则行为是未定义的.