Unexpected result when storing c_str() of temporary std::string in a variable

c++, memory-management, pointers, stdstring, temporary-objects

Solution

const char * ptr = returnStringMethod().c_str();

In above line a temp string is returned by the function which soon goes out of scope. (and destructor is called and memory is freed)

In later version you make a local copy of string and thus the behaviour is defined.

You can also use the following

const std::string &str = returnStringMethod();
const char * ptr = str.c_str();

Using const reference would lengthen the life of temporary variable until the reference is in scope and there would be no (explicit) unwanted copies.

Problem

I have a member function defined as below: ``` std::string returnStringMethod() { return /* some string */; } ``` The caller looks like this: ``` const char * ptr = returnStringMethod().c_str(); ``` This is returning some truncated string which I did not expect. However, the following works fine: ``` std::string str = returnStringMethod(); const char * ptr = str.c_str(); ``` What is happening here?

Original source

Related problems