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
553 views
in Technique[技术] by (71.8m points)

c - Why doesn't the compiler detect and produce errors when attempting to modify char * string literals?

Assume the following two pieces of code:

char *c = "hello world";
c[1] = 'y';

The one above doesn't work.

char c[] = "hello world";
c[1] = 'y';

This one does.

With regards to the first one, I understand that the string "hello world" might be stored in the read only memory section and hence can't be changed. The second one however creates a character array on the stack and hence can be modified.

My question is this - why don't compilers detect the first type of error? Why isn't that part of the C standard? Is there some particular reason for this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

C compilers are not required to detect the first error, because C string literals are not const.

Referring to the N1256 draft of the C99 standard:

6.4.5 paragraph 5:

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence; [...]

Paragraph 6:

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.

(C11 does not change this.)

So the string literal "hello, world" is of type char[13] (not const char[13]), which is converted to char* in most contexts.

Attempting to modify a const object has undefined behavior, and most code that attempts to do so must be diagnosed by the compiler (you can get around that with a cast, for example). Attempting to modify a string literal also has undefined behavior, but not because it's const (it isn't); it's because the standard specifically says the behavior is undefined.

For example, this program is strictly conforming:

#include <stdio.h>

void print_string(char *s) {
    printf("%s
", s);
}

int main(void) {
    print_string("Hello, world");
    return 0;
}

If string literals were const, then passing "Hello, world" to a function that takes a (non-const) char* would require a diagnostic. The program is valid, but it would exhibit undefined behavior if print_string() attempted to modify the string pointed to by s.

The reason is historical. Pre-ANSI C didn't have the const keyword, so there was no way to define a function that takes a char* and promises not to modify what it points to. Making string literals const in ANSI C (1989) would have broken existing code, and there hasn't been a good opportunity to make such a change in later editions of the standard.

gcc's -Wwrite-strings does cause it to treat string literals as const, but makes gcc a non-conforming compiler, since it fails to issue a diagnostic for this:

const char (*p)[6] = &"hello";

("hello" is of type char[6], so &"hello" is of type char (*)[6], which is incompatible with the declared type of p. With -Wwrite-strings, &"hello" is treated as being of type const char (*)[6].) Presumably this is why neither -Wall nor -Wextra includes -Wwrite-strings.

On the other hand, code that triggers a warning with -Wwrite-strings should probably be fixed anyway. It's not a bad idea to write your C code so it compiles without diagnostics both with and without -Wwrite-strings.

(Note that C++ string literals are const, because when Bjarne Stroustrup was designing C++ he wasn't as concerned about strict compatibility for old C code.)


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

...