根据C89标准字符串修改不确定的行为? [英] Is modification of string literals undefined behaviour according to the C89 standard?

查看:89
本文介绍了根据C89标准字符串修改不确定的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信,在C99,字符串的修改是不确定的行为。我没有这个标准的副本,但我有C1X(n1570),其中规定草案6.4.5条第7款:

I believe that in C99, modification of string literals is undefined behaviour. I don't have a copy of that standard but I do have a draft of C1X (n1570) which states in 6.4.5 paragraph 7:

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

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.

我已经找到了一个堆栈溢出<一个href=\"http://stackoverflow.com/questions/8981828/why-doesnt-the-compiler-detect-and-produce-errors-when-attempting-to-modify-cha\">question触及这个话题,包含乔纳森莱弗勒的评论:

I have found a Stack Overflow question that touches on this topic and contains the following comment from Jonathan Leffler:

本来,C89(C90)的标准并没有取缔修改文本,因为有标准的,将被它被打破之前写太多code。

Originally, the C89 (C90) standard did not outlaw modifying literals because there was too much code written before the standard that would be broken by it.

不过,我也看到很多的的类型的讨论的字符串和事实,他们是的char [N] ,而不是为const char [N] 。据我了解,这个决定是使大量的现有code会不会打破。

But I have also seen lots of discussion of the type of string literals and the fact that they are char[N] and not const char[N]. I gather that this decision was taken so that the large body of existing code would not break.

谁能给我一个明确的答案。是字符串修改UB在C89?

Can anyone give me a definitive answer. Is string literal modification UB in C89?

推荐答案

是的,他们是不可修改的C89。

Yes, they are non-modifiable in C89.

(C90,6.1.4)如果程序试图修改字符串文字两种形式,其行为是未定义

(C90, 6.1.4) "If the program attempts to modify a string literal of either form, the behavior is undefined"

即使在K&放大器; R第二版,也有对字符串的不变性报价

Even in K&R 2nd edition, there are quotes regarding the immutability of string literals.

(K&安培; R2,5.5)的结果是不确定的,如果你尝试修改字符串的内容

(K&R2, 5.5) "the result is undefined if you try to modify the string contents"

(K&安培; R2,附录C)字符串不再是可修改的,所以可以放在只读存储器

(K&R2, Appendix C) "Strings are no longer modifiable, and so may be placed in read-only memory"

在ANSI C89理由,存在为什么它是不可修改的说明:

In the ANSI C89 Rationale, there is an explanation of why it is non-modifiable:

(ANSI C89理由,3.1.4)字符串文字被指定为是不可修改的。该规范允许实现共享相同的文本字符串拷贝,放置在只读存储器字符串,并进行一定的优化。

(ANSI C89 Rationale, 3.1.4) "String literals are specified to be unmodifiable. This specification allows implementations to share copies of strings with identical text, to place string literals in read-only memory, and perform certain optimizations."

这篇关于根据C89标准字符串修改不确定的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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