#include <stdio.h>
int main() {
char *name = "Thank you";
name[0] = 'a';
printf("%s", name);
}
and it works fine:
My understanding is that name[0] = 'a' should not work.
So why is it working?
#include <stdio.h>
int main() {
char *name = "Thank you";
name[0] = 'a';
printf("%s", name);
}
and it works fine:
My understanding is that name[0] = 'a' should not work.
So why is it working?
C standard imposes no restriction on attempting to modify a string literal. However, if you attempt to modify a string literal, the outcome is undefined behaviour.
Quoting C11, chapter 6.4.5 (String literals)/P7
[...] If the program attempts to modify such an array, the behavior is undefined.
The fact that you think the program is allowing you to modify the content of the string literal is one of the many outcome of the UB.
Your understanding is almost correct, the program is indeed ill-formed, but that doesn't mean that it should malfunction or othewise fail, it invokes undefined behavior.
Unfortunately, one of the possible symptoms of undefined behavior is the appearence that the program is behaving as it should.
Undefined behavior as described in N1570 ISO/IEC 9899:201x §3.4.3
1 undefined behavior
Behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements.
2 NOTE
Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).