Your forgetting string literals which are part of the language.
jam@jam-desktop:~$ cat y.c
main()
{
char * s = "abc";
*s = 'c';
}
jam@jam-desktop:~$ ./y
Segmentation fault
But you're right that they are a part of the language."If the program attempts to modify such an array, the behavior is undefined."
Hence there is no requirement to segfault.
OpenSolaris/suncc, Jacques' program:
$ cat immutable.c
#include <stdio.h>
int main()
{
char * s = "abc";
*s = 'c';
printf("%s\n", s);
return 0;
}
$ cc -o immutable immutable.c
$ ./immutable
cbc
EDIT: I can't reply to you, so I have to take this route.
I also think that this behavior is not desirable. However,
I do not see the passage in the the standard that forbids
writable strings. On the contrary, in Annex J writable
string literals are explicitly allowed as an extension,
and I don't see any indication that the presence of
writable strings make an implementation non-conforming.Perhaps you could point to the passage in the standard that requires string literals to be immutable (your words, not mine) or that requires a compiler to issue a warning if a string literal is modified.
If you still wonder why I'm arguing this: It is not for the sake of nitpicking, but to support kabdib's post.
There are plenty of platforms that C runs on that are incapable of making anything immutable, including program text itself. That doesn't make C strings less immutable. Why isn't your compiler yelling at you for doing that? I think it's broken!
char *s = "Hi, Jacques"; // is immutable
char s[] = "Hi, Jacques"; // is writeable
"Hi, Jacques"[0] = 'S'; // is nonsensical