Intel Mac 上的总线错误,为什么?

发布于 2024-10-23 18:49:30 字数 302 浏览 2 评论 0原文

导致 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;
}

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

━╋う一瞬間旳綻放 2024-10-30 18:49:30

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

如果您将: 替换

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

为:

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

或: 之类的内容,

char text[] = "HI";

您会发现它会起作用,因为在这种情况下 text 是可修改的内存。

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.

紫轩蝶泪 2024-10-30 18:49:30

你不能抛弃const,它是UB。字符串常量是只读的,因此编译器可以将它们放入只读内存中。

用于

char text[] = "Hi!";

获取可修改的字符串。

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.

紫﹏色ふ单纯 2024-10-30 18:49:30
char *text = (char *)"HI";
text[0] = 'f';

这实际上是违反C++标准的。带引号的字符串被声明为 const 是有原因的。在您的情况下,它可能会将字符串存储为“代码数据”而不是常规“数据”的一部分。这与使“代码数据”区域只读的常见用法相结合,使得您无法写入带引号的常量字符串。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文