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.
getenvis a function, this shouldn't compile because you can't cast a function pointer to aconst char*by adding or removingconst. Similarly, thisconst_castis addingconst, not removing it, so it should be safe. Can we see your actual code?