为什么在更改非常量char *时出现分段错误? [英] Why a segmentation fault for changing a non-const char*?

查看:103
本文介绍了为什么在更改非常量char *时出现分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此代码,我遇到了细分错误:

With this code, I get a segmentation fault:

   char* inputStr = "abcde";
   *(inputStr+1)='f';

如果代码是:

   const char* inputStr = "abcde";
   *(inputStr+1)='f';

分配只读位置"会出现编译错误. 但是,对于第一种情况,没有编译错误.只是分配操作实际发生时的细分错误.

I will get compile error for "assigning read-only location". However, for the first case, there is no compile error; just the segmentation fault when the assign operation actually happened.

有人可以解释吗?

推荐答案

以下是标准在[2.13.4/2]部分中对字符串文字的说明:

Here is what the standard says about string literals in section [2.13.4/2]:

不以u,U或L开头的字符串文字是普通的字符串文字,也称为窄字符串文字.普通字符串文字的类型为"n const char的数组",其中n是如下定义的字符串的大小;它具有静态存储持续时间(3.7),并使用给定的字符进行了初始化.

A string literal that does not begin with u, U, or L is an ordinary string literal, also referred to as a narrow string literal. An ordinary string literal has type "array of n const char", where n is the size of the string as defined below; it has static storage duration (3.7) and is initialized with the given characters.

因此,严格来说,"abcde"具有类型

So, strictly speaking, "abcde" has type

const char[6]

现在,代码中发生的事情是隐式转换为

Now what happens in your code is an implicit cast to

char*

,以便允许分配.这样做的原因很可能是与C兼容.请在此处也进行讨论:

so that the assignment is allowed. The reason why it is so is, likely, compatibility with C. Have a look also at the discussion here: http://learningcppisfun.blogspot.com/2009/07/string-literals-in-c.html

完成转换后,您可以在语法上自由地修改文字,但由于编译器会在标准本身允许的范围内将文字存储在不可写的内存段中,因此操作失败.

Once the cast is done, you are syntactically free to modify the literal, but it fails because the compiler stores the literal in a non writable segment of memory, as the standard itself allow.

这篇关于为什么在更改非常量char *时出现分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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