Intel Mac 上的总线错误,为什么?
导致 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不允许您更改字符串常量,根据标准,这是未定义的行为。
如果您将: 替换
为:
或: 之类的内容,
您会发现它会起作用,因为在这种情况下
text
是可修改的内存。You are not allowed to change string constants, that's undefined behaviour as per the standard.
If you replace:
with something like:
or:
you'll find that it will work, because
text
in that case is modifiable memory.你不能抛弃
const
,它是UB。字符串常量是只读的,因此编译器可以将它们放入只读内存中。用于
获取可修改的字符串。
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
to get a modifiable string.
这实际上是违反C++标准的。带引号的字符串被声明为 const 是有原因的。在您的情况下,它可能会将字符串存储为“代码数据”而不是常规“数据”的一部分。这与使“代码数据”区域只读的常见用法相结合,使得您无法写入带引号的常量字符串。
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.