str.substr(5).c_str() error

I've got a pretty odd error in this code:
const char* cstr = str.substr(5).c_str();
Where str is an std::string.

If I run that, cstr == "". However, if I run
1
2
string str2 = str.substr(5);
const char* cstr = str2.c_str();

cstr gets the correct value.

Why can't I stack up substr() and c_str()?
Last edited on
I assume that str points to a string that is at least six characters long, no?
You are assuming that your temporary data allocation is persistent. Don't do that.
To elaborate on what Duoas is saying, substr returns a string. This string is a temporary object that is destroyed as soon as it is no longer being used (at the end of the line)

So at the end of the line, since the temporary string is destroyed, your 'cstr' pointer is left pointing to string data that no longer exists (bad pointer).
Ah, thanks. It's pretty obvious once you think about it, but it hadn't occurred to me that c_str() would return data that is "bound" to the string itself.

I was blind, but now I see.
Topic archived. No new replies allowed.