字符指针中的分段错误

Segmentation Fault in char pointer

当 运行 下面的代码时,我遇到了分段错误。这个错误的原因可能是什么?请帮忙

int main()
{
    char *str2 = "Hello";
    str2[3] = 'J';
    printf("%s\n",str2);
    return 0;
}

不允许修改字符串常量,在这种情况下会导致运行时错误。您可以通过将 str2 的声明更改为:

来修复它
char str2[] = "Hello";

这使它成为一个数组,而不是指向字符串常量的指针。

您不能修改 char* 用字符串文字初始化的变量指向的内存。它是只读的。

这是一个未定义的行为,因为您正试图修改 string literal 的内容。主要存储在只读位置 中的字符串文字。所以你不要修改它,否则它会调用未定义的行为。

C11 §6.4.5 字符串文字(第 7 段):

It is unspecified whether these arrays are distinct provided their elements have the appropriate values.If the program attempts to modify a string literal of either form, the behavior is undefined"