Possible Duplicate:
Why does this Seg Fault?
What is the difference between char a[] = “string”; and char *p = “string”;
Trying to understand why s[0]=’H’ fails. I’m guessing this has something to do with the data segment in the process memory but maybe someone better explain this?
void str2 (void)
{
char *s = "hello";
printf("%s\n", s);
s[0] = 'H'; //maybe this is a problem because content in s is constant?
printf("%s\n", s);
}
int main()
{
str2();
return 0;
}
It’s wrong because the C standard says that attempting to modify a string literal gives undefined behavior.
Exactly what will happen can and will vary. In some cases it’ll “work” — the content of the string literal will change to what you’ve asked (e.g., back in the MS-DOS days, it usually did). In other cases, the compiler will merge identical string literals, so something like:
…would print out
1a34, even though you never explicitly modifiedbat all.In still other cases (including most modern systems) you can expect the attempted write to fail completely and some sort of exception/signal to be thrown instead.