2

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;
}
Community
  • 1
  • 1
DriverDev
  • 124
  • 1
  • 7

3 Answers3

6

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:

char *a = "1234";
char *b = "1234";

a[1] = 'a';

printf("%s\n", b);

...would print out 1a34, even though you never explicitly modified b at 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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
2

You are trying to modify a string literal, which resides in implementation defined read only memory thereby causing an Undefined Behavior. Note that the undefined behavior does not warrant that your program crashes but it might show you any behavior.

Good Read:
What is the difference between char a[] = ?string?; and char *p = ?string?;?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

I think this behavior, a good or stern compiler should not allow since this is (char *s = "hello") pointer to constant i.e. modifying the contents will lead to undefined behavior if the compiler will not throw any error on this