在下面的代码中,结果是堆栈溢出。尽管两个字符串都存在空字符,因此 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;
}
最佳答案
错误不是堆栈溢出,而是修改字符串字面量。
str
是一个指向字符串字面量"Hello world"
的指针,修改字符串字面量是未定义的行为。
将 str
更改为:
char str[100] = "Hello world";
关于c - 带有指向字符数组指针的 strcpy 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25971223/