Where is the undefined behavior when using const_cast<>?

前端 未结 2 1735
情话喂你
情话喂你 2021-01-18 04:57

If I do:

const char* const_str = \"Some string\";

char* str = const_cast(const_str); // (1)

str[0] = \"P\"; // (2)

Where (wh

相关标签:
2条回答
  • 2021-01-18 05:15

    You are attempting to modify a constant string which the compiler may have put into a read-only section of the process. This is better:

    char str[32];
    strcpy(str, "Some string");
    str[0] = "P";
    
    0 讨论(0)
  • 2021-01-18 05:23

    Line (2) has undefined behaviour. The compiler is at liberty to place constants in read-only memory (once upon a time in Windows this would have been a "data segment") so writing to it might cause your program to terminate. Or it might not.

    Having to cast const-ness away when calling a poorly-defined library function (non-const parameter which should be const) is, alas, not unusual. Do it, but hold your nose.

    0 讨论(0)
提交回复
热议问题