const char *p = os1.str().c_str();
Here is the problem, in the above line.
os1.str()
returns a temporary string object by copying the internal string buffer. And you're taking .c_str()
of the temporary object, which gets destroyed at the end of the full expression. The result is, p
points to the destroyed object when you take it to print using std::cout
.
That is, your program invokes undefined behavior (UB).
Try this:
auto s = os1.str();
const char *p = s.c_str(); //s is not a temporary object anymore!
Now it gives correct output (and this is your code — luckily even coliru gives the same output as you observed on your machine. Note that this output is not guaranteed though precisely because the code invokes UB.).