c++ - 修改 char *const 字符串

标签 c++ c string pointers runtime-error

我知道 const char * 是指向 const char 的指针,而 char *const 是指向 char 的常量指针。 我正在用以下代码对此进行测试:

const char *s = "hello";    // Not permitted to modify the string "hello"
char *const t = "world";    // Not permitted to modify the pointer t

s = "hello2";   // Valid
// t = "world2";   // Invalid, gives compilation error

// *(s + 1) = 'a';    // Invalid, gives compilation error
*(t + 1) = 'a';       // Why does this not work?    

最后一行没有给出任何错误,但导致程序意外终止。为什么不允许修改t指向的字符串?

最佳答案

t 指向一个字符串文字 修改字符串文字 是未定义的行为。 C++ 草案标准部分 2.14.5 String literals 段落 12 说(强调我的):

Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation defined. The effect of attempting to modify a string literal is undefined.

C99 标准草案的相关部分是 6.4.5 String literals paragraph 6 说(强调我的 em>):

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

在典型的现代 Unix 平台上,您会在只读段中找到字符串文字,如果我们尝试修改它,将导致访问冲突。我们可以使用 objdump 来检查只读部分,如下所示:

objdump -s -j .rodata

我们可以在下面看到live example字符串文字确实会在只读 部分中找到。请注意,我必须添加 printf 否则编译器会优化掉字符串文字。示例`objdump 输出:

Contents of section .rodata:
 400668 01000200 776f726c 64002573 0a00      ....world.%s..

另一种方法是让 t 指向一个包含 string literal 拷贝的数组,如下所示:

char r[] = "world";    
char *const t = r ;

关于c++ - 修改 char *const 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19372952/

相关文章:

c++ - 如何在 C++ 中强制编译错误?

c - 我应该使用什么类型来表示 C 枚举的二进制?

javascript - 为了获得多维数组,在字符串中拆分字符串的一般解决方案是什么?

c++ - 在 Debug模式下运行时缓冲区溢出

c++ - C++中的特殊枚举

c++ - std::vector 在不知道元素类型的情况下插入

检查输入类型,无需退出程序并重新启动它

直接调用函数比通过 bash 脚本调用它花费更多的时间

python - 在大括号周围的字符串中添加单引号 - Python

java - 为什么编译器不能识别我的返回语句?