2

Why does the code below give me a segmentation fault.

int main()
{
    char *something = "hello\n";
    something[2] = 'a';   // doesn't work
    *(something+2) = 'a'; // this doesn't work either
    return 0;
}

But the following code works fine.

int main()
{
    char something[] = "hello\n";
    something[2] = 'a'; //works fine
    *(something+2) = 'a'; //works fine
    return 0;
}

The "something" variable is a char array in both so why can't I assign a character literal to the third element of the array in the first example?

user22119
  • 717
  • 1
  • 4
  • 18

1 Answers1

1

The compiler is free to put quoted strings into read only memory segments and merge duplicate quoted strings and otherwise assume you will never write into a quoted string. But the language depends on the fact that a quoted string pretends to be a char* even though it really makes sense only as a char const*

That language design choice that a quoted string is a char* was necessary for C compatibility, but is an odd behavior for those working in C++.

The syntax char something[] = "hello\n"; is another oddity of C compatibility and differs more than you might expect from the normal meaning of a quoted string. The quoted string might or might not ever exist at run time (whatever is easiest for the compiler). The char array is initialized to match what the quoted string would have been if it had existed. But then it is a char array, not a quoted string, so it is freely writable.

JSF
  • 5,281
  • 1
  • 13
  • 20