Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

c - Is modification of string literals undefined behaviour according to the C89 standard?

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.

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

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.

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.

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, they are non-modifiable in C89.

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

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

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

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

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

(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."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...