Hi,
this may be a FAQ - in my class today when discussing how gcc
generates code for x86, I was stumped when I showed an example of how
gcc handles attempts to modify (read-only) string literals/constants.
(I'm sending this to gcc rather than gcc-help because I'm asking for a
design rationale - I believe I understand the semantics of string
constants in C. If in appropriate, I'm happy to resend there.)
Specifically, I was surprised to see that gcc 4.1.2, when invoked with
-O, simply elided the offending statement s[0] = 'H' in the example
below.
int
main()
{
char * s = (char *)"hello"; // read-only
printf("%s\n", s);
s[0] = 'H'; // gcc -O elides this
printf("%s\n", s);
return 0;
}
Could someone briefly provide justification/rationale for this decision?
Is the rationale simply that since "the behavior of a program that
attempts to modify a string constant is undefined" (K&R) you felt
justified in silently discarding it (rather than letting it proceed or
cause a runtime error if the string literal is mapped in a read-only
section of the address space?)
I note that even though the compiler knows it is taking advantage of a
rule that allows it to produce code that contains undefined behavior,
there appears to be no warning option to alert the user. Notably, gcc
-Wall -Wwrite-string is silent for the above program.
Thanks.
- Godmar