Search code examples
c++pointerscharconstantsextern

C++ extern const char* not working as expected


I have worked with the extern keyword before but now I have a really strange problem.

First of all I have my common.hh File containing the declaration of extern variables:

//some extern declarations
extern const char* PATH;

In my main.cc I do the following (ignore the cout for now):

#include "common.hh"
const char* PATH;

int main(const int argc, const char* argv[]){
PATH = somePath.c_str();
//std::cout << PATH << std::endl; //will print the correct path
//std::cout << std::string(PATH) << std::endl; //will fix the problem occuring later
//some function calls to other files where PATH is used
//... somePath still in scope ...
//... somePath is about to be destroyed
}

Now I have my other files Other.hh and Other.cc where the problem occurs: First my Other.hh

#include "common.hh"
//function declarations and some other stuff

In Other.cc the problem when accessing PATH occurs:

#include "Other.hh"
void someFunction(...){
std::cout << PATH << std::endl; //When accessing PATH here again it prints garbage

In my file Other.cc I need the const char* PATH defined in main.cc but for some reason PATH has changed. The whole problem is fixed if I do std::string(PATH) somewhere in my main.cc as seen in the cout above. I don"t get what is wrong, all my other extern variables work just fine.

EDIT: Problem is fixed for now. I just did the following in main.cc:

std::string tmp = somePath;
PATH = tmp.c_str();

I just don't understand why this fixes the problem because in theory tmp and somePath should have the same scope and should not be destroyed until after the function call in other.cc was executed. In other words: my function call in other.cc is before the scope of somePath has ended.


Solution

  • The lifetime of somePath.c_str() is bound by the somePath variable. As soon as it goes out of scope, PATH points to memory that will be re-used.

    Can you make PATH a std::string instead of a char*? If not, you will have to duplicate the value of somePath.c_str() using strdup or something similar.