Question

This question is regarding the behavior I observed while using const_cast for making a char * const char *. I am aware that this casting is done implicitly and t working for me when the cast is being done implicitly.

The problematic code is:

#include <cstdlib>
int main() {
    const char * org_str = NULL;
    org_str = const_cast<const char*>(getenv("ENV_VAR")); // PROBLEM !!
}

As per the Linux man page getenv() takes const char * and returns char*. So, as per my understanding of const-correctness, I can do a const cast on char* without any issues.

So, my question is, why const_cast here giving me a UB (code is crashing) but as expected without const_cast(implicit casting) its working fine(So the problem has to be with the use of const_cast) ?

Please note, I know implicit cast is the way to go here, through this post I require the answer specifically for the behavior observed here.

EDIT:

Since the bug is non reproducible by fellow So'ers, I am assuming this as some weird runtime/compiler issue. But, do let me know if there is any mention of problems such as this in the standard.

For the time being I am accepting Mike's answer.

Was it helpful?

Solution

You are casting the function pointer, not the pointer returned by the function. Call the function first with (), then cast the result.

EDIT: I can't reproduce the problem. Here's the code I used:

#include <cstdlib>
#include <iostream>

using namespace std;
int main() {
    const char * org_str = NULL;
    org_str = const_cast<const char*>(getenv("PATH"));
    cout << "Got: " << org_str << endl;
}

Here's what I got:

$ g++ foo.cc -o foo.app
$ ./foo.app
Got: /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/X11R6/bin
$

BTW, the assignment to NULL is unnecessary; recommended practice is to use one of:

const char *org_str = const_cast<const char*>(getenv("PATH"));

const char *org_str(const_cast<const char*>(getenv("PATH")));

const char *org_str(getenv("PATH"));

OTHER TIPS

You don't need a const_cast<> to make something const, you only need it to take away the const-ness.

Also I don't believe the code you have there is correct at all, since getenv is a function and it looks like you're using it as a variable. Perhaps something like this would work:

const char * org_str = getenv("name-of-env");

It's, as far as I understand, not the return value of getenv you should cast, but the const char you have. As org_str is constant, you can't assign to it without using const_cast, which means you would need to do something like:

#include <cstdlib>
int main() {
    const char * org_str = NULL;
    const_cast<char*>(org_str) = getenv("ENV_VAR"); // NO PROBLEM !!
}

EDIT: As for having const_cast on the getenv, it makes no sense, as you don't assign to that and therefor will not have any violations of the const expression, as

org_str = getenv("ENV_VAR") will give you.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top