Question

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

Était-ce utile?

La solution

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()!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top