Red Hat Bugzilla – Bug 51113
ostrstream in c++ lib has a memory leak
Last modified: 2008-05-01 11:38:00 EDT
From Bugzilla Helper:
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.3) Gecko/20010801
Description of problem:
Using the ostrstream class in the c++ standard library causes a memory
leak. If a program uses a lot of them, then all the computer's memory can
I'll include a test program to demonstrate.
Steps to Reproduce:
1. Make program using ostrstream
2. Use the str() method to get a const char* to the string
3. Destructor doesn't clear memory
Test program (eg test.cc):
o << "Hello, world!" << '\0';
std::cout << o.str();
Compile with g++ test.cc
Watch memory usage of program increase.
This is a serious bug for c++ developers.
There's a workaround. Add
before the destructor is called.
Created attachment 26653 [details]
Patch to gcc sources to fix problem (untested)
Created attachment 26654 [details]
previous patch was reversed
Created attachment 26655 [details]
third time lucky!!!
I think libstdc++ is right:
sais in ostrstream::str () description that it
This means that after o.str() the string is managed by user who is responsible
for freeing it, unless o.freeze(0) is called.
You could e.g. stick the pointer returned by o.str() into global variable
and use it far after o has been destructed.
Note that g++ 3.0 works exactly the same way with your example, it leaks memory
too. But it is because of missing o.freeze(0) in your testcase.
Interesting, it seems there's some debate whether this is a bug or not. For
example, in the following link Compaq "fixed" their library to free the memory:
I think however, it's not a bug, after doing some research.
The solution, I suppose is to use ostringstream, but that's only a recent
addition to the standard :-(
My reading of the link you provided is that they weren't freeing the string
at all. ISO C++ in [depr.strstreambuf] sais clearly that the string should
be deleted only if strmode & allocated != 0 and strmode & frozen == 0.
In your testcase, strmode & frozen != 0, so it should not be deleted.