Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

basic_ostringstream::str dangling pointer

Tags:

c++

c++11

Recently I found the bug in the following code:

ostringstream o;
o << "some string";
const char* s = o.str().c_str(); // empty string instead of expected "some string"

This is explained by cppreference.com: the copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer.

I don't have any problem fixing this bug, however, I have many places in the projects, which look like this:

ostringstream o;
o << "error description";
throw my_exception(o.str().c_str());

...

my_exception::my_exception(const char* s) :
    message(s)     // message is std::string
{}

Does this code has undefined behavior, like the first code fragment?

like image 627
Alex F Avatar asked Sep 17 '26 18:09

Alex F


1 Answers

No, message(s) is a std::string so you take a copy of the contents of the char buffer at that point.

The temporary lasts for the scope of the function you call it with - in this case the constructor.

like image 162
DanDan Avatar answered Sep 20 '26 06:09

DanDan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!