2

Why does the value of text1 change after reading out y in this piece of code?

void func()
{
    int value1 = 5;
    double value2 = 1.5;
    std::ostringstream x, y;

    x << value1;
    y << value2;


    const char *text1 = x.str().c_str();
    fprintf(stderr, "text1: v=%s, p=%p\n", text1, &text1);
    const char *text2 = y.str().c_str();
    fprintf(stderr, "text1: v=%s, p=%p\ntext2: v=%s, p=%p\n", text1, &text1, text2, &text2);
}

Output:

text1: v = 5, a = 0xbfcfd508

text1: v = 1.5, a = 0xbfcfd508

text2: v = 1.5, a = 0xbfcfd510

Civing
  • 353
  • 3
  • 12

1 Answers1

8

After you have evaluated the str().c_str() expression, the temporary std::string instance created by the call to str() is released and your char pointer points into Nirvana. You need to store the return value of str()!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    the moral of the story : avoid c_str(), specially of a temporary – BЈовић Apr 25 '12 at 12:54
  • 3
    The return value of [c_str](http://www.cplusplus.com/reference/string/string/c_str/) is only guaranteed valid until the next non-const operation on the object. The destructor is non-const. So you're storing a result that becomes invalid before you use it. – David Schwartz Apr 25 '12 at 12:54