0

I have the following code:

int main()
{
    char *input = "why isn't this possible?";
    input[0] = 'W';
    return 0;
}

I want to modify the first value of the string, but it appears to cause an access violation on the input[0] = 'W'; line.

Any ideas why this is happening. Oddly I don't recall this error happening on my old machine running Visual Studio, but happens with GCC and Pellas C.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
BugHunterUK
  • 8,346
  • 16
  • 65
  • 121

2 Answers2

3

First of all, what your attempting to modify is not a string, it's a string literal.

Yes, you see different behaviour in different cases because this attempt is mentioned to exhibit undefined behaviour in C standard.

Quoting C11, chapter 6.4.5, String literals

[...]If the program attempts to modify such an array, the behavior is undefined.

To achieve the expected output, you can simply use an array, initialized by the string literal and them attempt to modify the array element. Something like:

int main(void)
{
    char input[ ] = "why isn't this possible?";  // an array
    input[0] = 'W';                              // perfectly modifiable
    return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Any attempt to modify a C string literal has undefined behaviour. A compiler may arrange for string literals to be stored in read-only memory (protected by the OS, not literally ROM unless you're on an embedded system). But the language doesn't require this; it's up to you as a programmer to get it right. Try this if you want the functionality:

int main()
{
    char input[] = "why isn't this possible?";
    input[0] = 'W';
    return 0;
}

Otherwise to learn more on it, check this answer out: Char* and char[] and undefined behaviour

Mohit Sharma
  • 338
  • 2
  • 13