带有指向字符数组的strcpy函数

Siy*_*iya 0 c stack-overflow pointers strcpy

在下面的代码中,结果是堆栈溢出.尽管两个字符串都有空字符,但strcpy循环应该终止,因为源字符串具有空字符.为什么发生堆栈溢出?

#include <stdio.h>
#include<strings.h>
int main(void) {
    char *str="Hello world";
    char *str1="Good morning";
    strcpy(str,str1);
    printf("%s",str);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Yu *_*Hao 7

错误不是堆栈溢出,而是修改字符串文字.

str是指向字符串文字的指针,"Hello world"修改字符串文字是未定义的行为.

更改str到:

char str[100] = "Hello world";
Run Code Online (Sandbox Code Playgroud)