英特尔Mac上的总线错误,为什么?

0 c++ string bus-error

导致EXC_BAD_ACCESS信号的测试程序.为什么这会导致总线错误?我想将'HI'改为'fI'.

//BUS ERROR TEST

#include <iostream>

void test(char *text)
{
    text[0] = 'f';
}

int main()
{
    char *text = (char *)"HI";
    test(text);
    std::cout << text << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 5

您不能更改字符串常量,这是根据标准的未定义行为.

如果你替换:

char *text = (char *)"HI";
Run Code Online (Sandbox Code Playgroud)

有类似的东西:

char text[3];
strcpy (text, "HI");
Run Code Online (Sandbox Code Playgroud)

要么:

char text[] = "HI";
Run Code Online (Sandbox Code Playgroud)

你会发现它会起作用,因为text在那种情况下它是可修改的内存.