Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the undefined behavior when using const_cast<>?

If I do:

const char* const_str = "Some string";

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

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

Where (which line) exactly is the undefined behavior ?

I've been searching a lot for this on SO but haven't found any explicit and precise answer (or at least, none that I could understand).

Also related: if I use an external library which provides this kind of function:

// The documentation states that str will never be modified, just read.
void read_string(char* str);

Is it ok to write something like:

std::string str = "My string";

read_string(const_cast<char*>(str.c_str()));

Since I know for sure that read_string() will never try to write to str ?

Thank you.

like image 904
ereOn Avatar asked Apr 04 '11 07:04

ereOn


People also ask

Is const_cast undefined behavior?

Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior. So yes, modifying constant variables is undefined behavior.

What is the use of const_cast in C++?

const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object. const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.

Can you cast away const in C?

The compiler does allow the *c = 30 , but the behavior of this statement is undefined. If you cast away the constness of an object that has been explicitly declared as const , and attempt to modify it, the results are undefined.

Is const_cast safe?

const_cast is safe only if you're casting a variable that was originally non- const . For example, if you have a function that takes a parameter of a const char * , and you pass in a modifiable char * , it's safe to const_cast that parameter back to a char * and modify it.


1 Answers

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.

like image 85
RobH Avatar answered Sep 19 '22 10:09

RobH