Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

g++: crash when accessing ostringstream::str().c_str()

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);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading