When you declare a string the way you've done, the compiler is allowed to do several things with it you may not expect. These include string merging (where multiple identical strings are actually only stored once), and storage in an area of memory that is write protected (note: it is not required to do either of these things, but it may).
In your case, it looks like the string got stored in write-protected memory. Telling the compiler to ignore this, by using const_cast, will trigger a CPU-exception, which will cause your program to terminate.
There is a simple solution though, which is to declare your string in a way that is modifyable:
char str [] = "Hello";
char* mstr = str;
mstr[1] = 'R';
Now it is an array you can legally modify as much as you want. No string merging will take place, and the data will not be stored in write-protected memory - and in fact you no longer need to const_cast either.
In general it is best not to use const_cast unless you know very, very clearly what you are doing. In my experience that mostly happens when interfacing to badly-written (usually C) APIs that take char *
instead of const char *
.