开发者

Contents changed(cleared?) when access the pointer returned by std::string::c_str()

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 runnin开发者_如何转开发g 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?


the string object will be alive as a auto var so the pointer should be valid till the end of this function,right?

Wrong. The temporary returned by the conf() function call lives as long as the full expression it is part of, not for the length of the function containing the call.


const char* p = conf().c_str();

The temporary string returned by conf() would die as soon as ; is encountered. So it is not a good idea to get pointer to the internal contents of the string. Since the string gets destroyed, p will point to invalid memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜