Search code examples
c++undefined-behaviorconst-correctnessconst-cast

Undefined behavior when adding a const with const_cast?


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.


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"));