尝试访问 C 中字符串上的字符时出现总线错误 [英] bus error when trying to access character on a string in C

查看:27
本文介绍了尝试访问 C 中字符串上的字符时出现总线错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经多次使用这行代码(更新:当 string 是函数的参数时!),但是当我现在尝试这样做时,我收到了总线错误(gcc 和 clang).我正在复制最简单的代码;

char *string = "这是一个字符串";字符 *p = 字符串;p++;*p='x';//这条线会导致总线错误printf("字符串是 %s\n",string);

为什么我无法使用 p 指针更改字符串的第二个字符?

解决方案

您正在尝试修改只读内存(存储字符串文字的位置).如果您需要修改该内存,您可以改用 char 数组.

char str[] = "这是一个字符串";str[0] = 'S';/* 工作 */

<小时><块引用>

这行代码我用过很多次了..

我当然希望不会.充其量你会得到一个段错误(我说充其量"是因为尝试修改只读内存是未指定的行为,在这种情况下任何事情都可能发生,而崩溃是可能发生的最好的事情).

当您声明一个指向字符串文字的指针时,它指向数据段中的只读内存(如果您愿意,请查看程序集输出).将您的类型声明为 char[] 会将该文字复制到函数的堆栈中,从而允许在需要时对其进行修改.

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?

解决方案

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.

char str[] = "This is a string";
str[0] = 'S'; /* works */


I have used this line of code many times..

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.

这篇关于尝试访问 C 中字符串上的字符时出现总线错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆