尝试访问 C 中字符串上的字符时出现总线错误
我已经多次使用这行代码(更新:当字符串是函数的参数时!),但是当我现在尝试这样做时,我收到总线错误(无论是使用 gcc 还是 clang)。我正在重现最简单的代码;
char *string = "this is a string";
char *p = string;
p++;
*p='x'; //this line will cause the Bus error
printf("string is %s\n",string);
为什么我无法使用 p 指针更改字符串的第二个字符?
I have used this line of code many times (update: when string was a parameter to the function!), however when I try to do it now I get a bus error (both with gcc and clang). I am reproducing the simplest possible code;
char *string = "this is a string";
char *p = string;
p++;
*p='x'; //this line will cause the Bus error
printf("string is %s\n",string);
Why am I unable to change the second character of the string using the p pointer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在尝试修改只读内存(存储字符串文字的位置)。如果需要修改该内存,可以使用字符数组。
我当然希望不会。最多你会得到一个段错误(我说“最好”是因为尝试修改只读内存是未指定的行为,在这种情况下任何事情都可能发生,而崩溃是可能发生的最好的事情)。
当您声明一个指向字符串文字的指针时,它指向数据段中的只读内存(如果您愿意,请查看汇编输出)。将类型声明为 char[] 会将该文字复制到函数的堆栈上,从而允许在需要时对其进行修改。
You are trying to modify read only memory (where that string literal is stored). You can use a char array instead if you need to modify that memory.
I sure hope not. At best you would get a segfault (I say "at best" because attempting to modify readonly memory is unspecified behavior, in which case anything can happen, and a crash is the best thing that can happen).
When you declare a pointer to a string literal it points to read only memory in the data segment (look at the assembly output if you like). Declaring your type as a char[] will copy that literal onto the function's stack, which will in turn allow it to be modified if needed.