Any string literal in C++ and C (for example "Hello"
in your code) is of type const char [6]
and can implicitly be assigned to any const char *
value:
const char * str="Hello";
indicating that it resides in memory marked as read-only by the operating system (you should have gotten a compiler warning). Therefore an exception will be thrown when you try to change that memory location.
The reason why the compiler puts this in read-only memory is because you may be using another identical (or even similar) string literal "Hello"
in a different part of your code. By marking the memory location of the string literal as read-only, the compiler only needs to store the string literal once in memory.
Note also, that the C++ standard does not require the compiler putting the string literal into read-only memory, it just says that modifying a string literal is undefined behaviour. In practice however, a string literal is stored in read-only memory on any modern operating system or compiler.