I have a function which shall return a char*. Since I have to concatenate some strings, I wrote the following line:
std::string other_text;
// ...
func((\"te
It is safe to call methods of temporary variables, but not safe to return a char* of a temporary variable for later use.
This char* points to a buffer that will be freed soon. Once it is freed you will have a pointer to an invalid region in memory.
Instead please return an std::string object.
The C-string returned by calling c_str() on the temporary will be valid until the next call to c_str() on the temporary, which can never happen. The temporary itself hangs around to the end of the full expression it is part of (the return statement).
If you were returning a std::string, everything would be hunkydory, as the string's copy constructor would be invoked in the return to take a copy. If you return a char *, then all bets are off, as the value you are returning will be disposed of when the function exits. This doesn't have anything specifically to do with the temporary, it is a general problem when returning char * - prefer to return std::strings instead.
A generated pointer will be good for as long as the temporary is still around, which is normally until the end of the expression. The exceptions are when a temporary is used in an initializer (in which case it lasts until the initialization is over), or when bound to a reference. A temporary in a function return statement lasts until the function exits (unless bound to a reference). Once the temporary lifetime is over, the temporary is destroyed. In this case, it means that the string destructor runs, and therefore the memory for the characters is freed. In other words, once the value is returned, it's guaranteed invalid.
You could pass the string itself back, returning it as a const reference. You could copy the .c_str() to newly allocated memory, and pass that back (as a pointer or smart pointer). Either of those would work.
The lifetime of temporaries is covered in section 12.2 of the C++ standard. According to the standard, you're returning a pointer to freed memory.
You are allowed to call methods on temporaries, however you have to be careful about object lifetimes -- in particular, if you have a function that returns c_str()
called on a temporary std::string
, that string object will be destroyed when the function returns.
Your code above suffers from this problem.