开发者

Bus Error on Intel Mac, why?

Test program which causes a EXC_BAD_ACCESS signal. Why does this cause a bus error? I want 开发者_如何转开发to change the 'HI' to '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;
}


You are not allowed to change string constants, that's undefined behaviour as per the standard.

If you replace:

char *text = (char *)"HI";

with something like:

char text[3];
strcpy (text, "HI");

or:

char text[] = "HI";

you'll find that it will work, because text in that case is modifiable memory.


You must not cast away const, it's UB. The string constants are read-only, so the compiler is allowed to put them into read-only memory.

Use

char text[] = "Hi!";

to get a modifiable string.


char *text = (char *)"HI";
text[0] = 'f';

This is actually against the C++ standard. Quoted strings are declared const for a reason. In your case, it probably stores the string as part of your "code data" rather than regular "data". This, combined with the common usage of making the "code data" area read only makes it so that you won't be able to write to quoted constant strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜