I have to maintain some legacy codes,parts of it look like the following:
/* this class reads a ini file which looks like this:
key = value
*/
class Config{
// ..
public:
string conf(const char* key)
{
vector<string> v;
//..
v = func(); //this function returns a vector<string>
return v[1];
}
};
void test()
{
// a globla Config object cfg is initialized outside
const char* p = cfg.conf("key1").c_str();
// the string object will be alive as a auto var
// so the pointer should be valid till the end of this function,right?
// ... lots of steps, but none of them would access the pointer p
some_call(cfg.conf("key2").c_str());
some_call(cfg.conf("key3").c_str());
some_call(cfg.conf("key4").c_str());
// the above calls never fail
// but when try to access p here, SOMETIMES the contents would change ... Why?
/* the platform is solaris 64 bit
compiler is sun workshop 12
my code is compiled as
ELF 32-bit MSB relocatable SPARC32PLUS Version 1, V8+ Required
but need to link with some shared lib which are ELF 32-bit MSB
dynamic lib SPARC Version 1, dynamically linked, stripped
*/
}
The original code has been running for several years and never failed(pure luck?).Recently we decided to migrate it to a newer platform and the problem described in the comments starts popping up.
Neil Butterworth and aJ have pointed out the temp string obj in this sentence:
const char* p = cfg.conf("key1").c_str();
will die immediately when ; is reached.Although in my test the access to key2,key3,key4 never failed,I guess they are actually not safe too,right?