The code below fails on gcc 9.4.0. Is this just a bug, or have I done something stupid?
log
declares an ostringstream
object, writes a filename and a line number to it, and attempts to do something with the object's underlying str().c_str()
.
Valgrind shows this crashing at the pointer access. The output I get is:
foo.cc, line 100
cptr is at 0x55c45e8f00c0, and is
#include <iostream>
#include <sstream>
#include <cstdarg>
using std::cout;
using std::ostringstream;
void log(const char *fname, int lineno) {
ostringstream outstr;
outstr << fname << ", line " << lineno;
cout << outstr.str() << '\n'; // prints Ok
const char *cptr = outstr.str().c_str();
cout << "cptr is at " << (void*) cptr << ", and is " << cptr; // crash
}
int main() {
log("foo.cc", 100);
}
CodePudding user response:
std::ostringstream::str()
returns a temporary string which will be destructed at the end of the line, this then means cptr
is a dangling pointer.
Try:
std::string str = outstr.str();
const char *cptr = str.c_str();
cout << "cptr is at " << (void*) cptr << ", and is " << cptr;