string concatenation using streams returns junk

69 Views Asked by At

I probably should start stating that I'm pretty new with C++, and, since I come from a higher level language, I may be missing some technical issues that I can't identify.

I have the following method:

const char * Point::toString() const {
    std::ostringstream stream;
    stream << "[" << x << ", " << y << "]"; //[3, 5] for example
    return stream.str().c_str();
}

I'm then calling it like this:

Point p1 (3, 5);
std::cout << p1.toString() << std::endl;

However, this prints some junk.

What am I doing wrong? Also, is my toString() method really efficient? Am I leaking memory by allocating a new char * and never freeing it?

2

There are 2 best solutions below

0
leemes On BEST ANSWER

The char pointer returned by string::c_str() is only valid for the lifetime of the string (and only when it is not modified).

But stream.str() returns a temporary string object, which you need to store somewhere. Otherwise it will be destroyed after that exact statement you call that function.

But even if you write

string result = stream.str();
return result.c_str();

then you destroy the string object inside of the function, invalidating the char pointer returned by c_str() and resulting in undefined behavior as soon as it is used (dereferenced).

In the end, the best is to just return a string:

return stream.str();
0
FunkyCat On

You can just do return strdup (stream.str().c_str()), but you should manage this memory by yourself.