1

I've been trying to append an integer to a string, and I've tried several solutions here, including:

std::stringstream ss;

ss << gvHours << "\'" << gvMinutes << "\"" << gvSeconds << ":" << gvTicks;

std::string output(ss.str());
return output.c_str();

and

std::stringstream ss;
std::string output = "";

ss << gvHours << "\'" << gvMinutes << "\"" << gvSeconds << ":" << gvTicks;

output = ss.str();
return output.c_str();

The first one gives me an empty string, and the second gives me an unreadable character that Notepad++ displays as "SOH" in a black box. Does anyone have any idea what I'm doing wrong?

Kelvin Shadewing
  • 303
  • 2
  • 16
  • 3
    See http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope. It's likely the cause of your problem. And depending on how you view the string, it could be empty simply because it consists of invisible characters. For example, SOH is the "Start of Header" control character (ASCII code 2). – chris Sep 12 '15 at 20:19
  • Why would you return a C-string anyway? lol – Lightness Races in Orbit Sep 12 '15 at 21:39

2 Answers2

4

Yes, this part

return output.c_str();

is broken.

When you take c_str() from a std::string, you are just getting a c-style pointer to the contents of that string. But you are not getting ownership of the data underlying that string. As soon as you return from the function, that stringstream and string are destroyed (as they are local variables) and the c_str() is a dangling pointer. So the whole thing is undefined behavior.

Chris Beck
  • 15,614
  • 4
  • 51
  • 87
1

I fixed it. Here's the code I got that works:

std::stringstream ss;
std::string output;

ss << gvHours << "\'" << gvMinutes << "\"" << gvSeconds << ":" << gvTicks;

output = ss.str();
return output;

And in the function where it was needed:

fprintf(gvLog, ">: %s\n", timeString().c_str());
Kelvin Shadewing
  • 303
  • 2
  • 16