This is fine:
// This creates a temp string
std::string temp = std::to_string(channel_id2);
// This is fine, because temp is a variable (and so exists in memory)
const char *sz2 = temp.c_str();
However, when you do:
const char *sz2 = std::to_string(channel_id2).c_str();
The order of operations is:
- Call
std::to_string
, which generates a temporary string object.
- Use
c_str()
to get a pointer to the temporary string contents
- Free the temporary string (thus freeing the memory that sz2 is pointing too)
The result is that sz2 is pointing at nothing valid, and so you get nonsense results printed out
Or to translate your one line of code across multiple lines, this is what is happening:
const char *sz2; //< uninitialised
// scope the lifespan of the temporary
{
// generate temp
std::string temp = std::to_string(channel_id2);
// grab address..
sz2 = temp.c_str();
// at this point, the destructor of temp is called...
}
// now sz2 is invalid from here