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?
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\n", 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.)
Compilers can detect the first "error".
In modern versions of gcc, if you use -Wwrite-strings, you'll get a message saying that you can't assign from const char*
to char*
. This warning is on by default for C++ code.
That's where the problem is - the first assignment, not the c[1] = 'y'
bit. Of course it's legal to take a char*
, dereference it, and assign to the dereferenced address.
Quoting from man 1 gcc
:
When compiling C, give string constants the type "const char[length]" so that
copying the address of one into a non-"const" "char *" pointer will get a warning.
These warnings will help you find at compile time code that can try to write into a
string constant, but only if you have been very careful about using "const" in
declarations and prototypes. Otherwise, it will just be a nuisance. This is why we
did not make -Wall request these warnings.
So, basically, because most programmers didn't write const-correct code in the early days of C, it's not the default behavior for gcc. But it is for g++.
-Wwrite-strings
seems to do what you want. Could have sworn that this was part of -Wall
.
% cat chars.c
#include <stdio.h>
int main()
{
char *c = "hello world";
c[1] = 'y';
return 0;
}
% gcc -Wall -o chars chars.c
% gcc -Wwrite-strings -o chars chars.c
chars.c: In function ‘main’:
chars.c:5: warning: initialization discards qualifiers from pointer target type
From the man pages:
When compiling C, give string constants the type "const char[length]" so that copying the address of one into a non-"const" "char *" pointer will get a warning. These warnings will help you find at compile time code that can try to write into a string constant, but only if you have been very careful about using "const" in declarations and prototypes. Otherwise, it will just be a nuisance. This is why we did not make -Wall request these warnings.
When compiling C++, warn about the deprecated conversion from string literals to "char *". This warning is enabled by default for C++ programs.
Note the "enabled by default for C++" is probably why I (and others) think -Wall
covers it. Also note the explanation as to why it isn't part of -Wall
.
As for relating to the standard, C99, 6.4.5 item 6 (page 63 of the linked PDF) reads:
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.
char* c = strdup("...");
would make c[1]
sensible. (Removed rant on C) Though an intelligent compiler could/does warn against this, C traditionally is machine near, without (bounds/format/...) checking and other such "needless" overhead.
lint
is the tool for detecting such errors: that a const char*
was assigned to a char*
. It would also mark a char c = c[30];
(No longer type dependent, but also addressing error.) As it would be nice to have declared c as const char*
. C is an older language with a tradition of leniency and operating on many platforms.
来源:https://stackoverflow.com/questions/8981828/why-doesnt-the-compiler-detect-and-produce-errors-when-attempting-to-modify-cha