修改char * const的字符串 [英] Modifying a char *const string

查看:157
本文介绍了修改char * const的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道为const char * 是一个指向一个const char,而 char * const的是一个常数指针为char。
我测试这在下面的code:

I know that const char * is a pointer to a const char, while char *const is a constant pointer to a char. I am testing this in the following code:

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 字符串字面的段落的 12 的说(的重点煤矿的):

t is pointing to a string literal it is undefined behavior to modify a string literal. The C++ draft standard section 2.14.5 String literals paragraph 12 says(emphasis mine):

不管所有的字符串文字是不同的(也就是说,存储在非重叠的对象)是实现定义。 试图修改字符串文本的影响是不确定

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 字符串字面的段落的 6 的它说(重点煤矿的):

The relevant section from the C99 draft standard is 6.4.5 String literals paragraph 6 which says(emphasis mine):

这是不确定的,这些阵列是否提供了不同的元素都在
  适当的值。 如果该程序试图修改这样的阵列,该行为是
  不确定的。

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的的检查只读部分如下:

On a typical modern Unix platform you will find string literals in the read-only segment which would result in a access violation if we attempt to modify it. We can use objdump to inspect the read-only section as follows:

objdump -s -j .rodata

我们可以在下面的活生生的例子看到中的字符串的确会发现在只读的部分。请注意,我不得不添加一个的printf ,否则编译器将优化出来的字符串。样品`的 objdump的的输出:

we can see in the following live example that the string literal will indeed be found in the read-only section. Note that I had to add a printf otherwise the compiler would optimize out the string literal. Sample `objdump output:

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

这是另一种办法是让 T 点与副本的阵列的字符串的像这样:

An alternative approach would be to have t point to an array with a copy of a string literal like so:

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

这篇关于修改char * const的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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