From Bugzilla Helper:
User-Agent: Mozilla/4.76 [en] (X11; U; Linux 2.2.16-22 i686)
Description of problem:
An error occurs where garbage is added to the end of ostrstream strings.
This occurs when a function is called from a catch block when the function
allocates the ostrstream locally.
Steps to Reproduce:
Compile and run the following code:
os << "hello" << endl;
cout << os.str() << endl;
int main( int argc, char* const* argv )
throw( "error" );
catch( const char* err )
Actual Results: hello
Expected Results: hello
This problem does not occur when the ostrstream is local to the main
routine or if called from outside the catch block.
I would classify this with loss of data as printing of information is
trashed. (loss of data)
I had another problem that wasn't so easily isolated, but is similar. When I
print out "" it is sometimes replaced with "(null)". This is a consistent bug in
my code, but I can't seem to get a simple test case to show it.
The char* the str() function returns isn't null terminated!!
You need to do
o << "Hi there" << endl << '\0';
Yeah, either that or os << "hello" << endl << ends;
Yes, that is the obvious workaround. However, str() is supposed to add the string terminator. The programmer is NOT supposed to do it manually. Notice
that this only happens in the above test case which suggests a subtle problem with the try/catch mechanism. Since I can't PROVE that str() is supposed
to add the null terminator (although after years of programming C++ I've never had a problem with it), I'll concede that it is not an official bug.
The above URL clearly states that you HAVE TO do it manually and str()
is not supposed to do it for you.
Checking libstdc++-v3 from GCC 3.0.1, it has exactly the same behaviour.
Reading [depr.strstreambuf] section in ISO C++ does not say anything that
str() should do it, it should just freeze() and then return the beginning.