0

I am new to C++. I have a program:

#include <iostream>

int main()
{
   char* str = "Test";
   *str = 'S';
}

The question is, why *str = 'S' crashes the program? As far as I know str must be pointing to the first character of the string (well, char array), so in theory I should be able to modify it. Is it because the memory is read-only for defined constant values? I am using gcc 5.3.0.

Mr.Pricky
  • 37
  • 7

1 Answers1

3

why *str = 'S' crashes the program?

Because you're not allowed to modify string literals. The C++ standard allows them to be stored in read-only memory.

In fact, if you enable compiler warnings, you get:

prog.cc:5:16: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
    char* str = "Test";
                ^~~~~~

Always use const char* when pointing to string literals:

Emil Laine
  • 41,598
  • 9
  • 101
  • 157