Search code examples
c++c++11castingconstantsconst-cast

const_cast usage giving me runtime exception


i have just started learning/exploring about const_cast and was experimenting with it when i found that after using const_cast,i get runtime error if i try to modify the data.

Basically i am dong something like

void main()
{
const char* str = "Hello";
char* mstr = const_cast<char*>(str);
mstr[1] = 'R';//<----- i get runtime exception on this line
}

is it happening because the string "Hello" is being stored somewhere in memory which cannot be modified.It would be great if someone can throw more light on this.


Solution

  • A string literal is const, by definition, so any modification of one gives undefined behaviour.

    You are using const_cast to create a non-const pointer to char (i.e. mstr) through which the compiler allows you to modify the string literal.

    Doing that does not change the basic fact that modifying a string literal gives undefined behaviour. All the const_cast does is give you is a pointer, which you can use to modify the string literal without the compiler complaining. The compiler is not required to do anything to the string literal (e.g. store it in modifiable memory) to make that operation become valid. Modifying the string literal through mstr is therefore still undefined behaviour. One possible symptom of undefined behaviour is a runtime error.