为什么我无法编辑 char* 中的字符?
下面是一个非常简单的例子。它在 Mac OS X (Snow Leopard) 上使用 gcc 可以正常编译。在运行时它输出总线错误:10.这里发生了什么?
char* a = "abc";
a[0] = 'c';
Below is an exceedingly simple example. It compiles fine using gcc on Mac OS X (Snow Leopard). At runtime it outputs Bus error: 10. What's happening here?
char* a = "abc";
a[0] = 'c';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的代码将
a
设置为指向"abc"
的指针,这是无法修改的文字数据。当您的代码违反此限制并尝试修改该值时,就会发生总线错误。尝试这样做:
创建一个 char 数组(在程序的正常数据空间中),并将字符串文字的内容复制到数组中。 现在您应该可以毫无困难地对其进行更改。
Your code sets
a
to a pointer to"abc"
, which is literal data that can't be modified. The Bus error occurs when your code violates this restriction, and tries to modify the value.try this instead:
That creates a char array (in your program's normal data space), and copies the contents of the string literal into your array. Now you should have no trouble making changes to it.
您正在尝试修改字符串常量。使用这个代替:
You are trying to modify a string constant. Use this instead:
这
依赖于从 const char[](字符串文字的类型)到 char* 的危险隐式转换。 (在 C++ 中,这种转换已被弃用十多年了。不过,我不了解 C。)
不得更改字符串文字。
This
relies on a dangerous implicit conversion from
const char[]
(the type of a string literal) tochar*
. (In C++ this conversion has been deprecated for more than a decade. I don't know about C, though.)A string literal must not be altered.
char *str = "string";
在这种情况下,它被视为只读文字。它类似于编写const char *str = "string"
。也就是说,指针str
指向的值是一个常量。尝试编辑将导致总线错误。char *str = "string";
In such a case it is treated as a read only literal. It is similar to writingconst char *str = "string"
. Which is to say that the value pointed to by the pointerstr
is a constant. Trying to edit will result in BUS ERROR.char *a = "abc"
是存储在 ELF 二进制文件的.data
部分中的常量字符串。您不允许修改此内存,如果您这样做,在某些情况下会发生未定义的行为,它不会给出错误,但不会修改内存,在您的情况下,您会收到总线错误,因为您正在尝试访问通常无法访问的内存(例如写作目的)。char *a = "abc"
is a constant string stored in the.data
section of an ELF binary. You are not allowed to modify this memory and if you do you incur undefined behavior in some cases it will give no error but not modify the memory in your case you get a bus error because you are attempting to access memory that you normally cannot (for writing purposes).