0

Possible Duplicate:
Why does char* cause undefined behaviour while char[] doesn’t?

Please have a look at the code below

int main (int argc, char* argv[])
{   
    char* s = "Hello world!";
    s[0] = 'X';
    return 0;
}

where do the seg fault come from in this code?

Update: On the contrary the code below does not give seg fault, why?

int main (int argc, char* argv[])
{   
    char s[] = "Hello world!";
    s[0] = 'X';
    return 0;
}
Community
  • 1
  • 1
daNullSet
  • 669
  • 2
  • 6
  • 16
  • 2
    See the duplicate. In short, `char *s = "Hello World!";` lets `s` point to (the first character of) a string literal, and attempting to modify a string literal is undefined behaviour, often a crash because they are stored in read-only memory. `char s[] = "Hello World!";` creates a writable `char[13]`. – Daniel Fischer Dec 24 '12 at 02:49
  • Can we have a separate tag for this particular dupe? `char *variable ="string"; variable[0]='ch';`? ;) – anishsane Dec 24 '12 at 06:39

1 Answers1

3

"Hello world!" is a static string, you can not change it.

xdazz
  • 158,678
  • 38
  • 247
  • 274