Visual C++ 2005 stringstream leak

I spent about five or six hours on Friday last week chasing down a memory leak that had appeared in some software at work that had previously been trouble free. I eventually tracked the leak down to a library used in multiple products that didn’t seem to leak elsewhere. Every time I used the library the application leaked 4k.

After a lot of building and testing, I tracked down the leak to a simple instantiation of the stringstream class from the standard library. This class leaks 4k every time it is instantiated due to, I believe, multiply inherited base classes both allocating the same buffer. This may also affect fstream as well.

The fix (for many use cases) is to replace stringstream with ostringstream which doesn’t leak.

As is so often the case, once I knew what was leaking I found references to it all over the Internet:

MSDN Forums

Len Holgate’s Blog

Microsoft Product Feedback

According to the product feedback site, this bug has been fixed for the next version (which hopefully includes SP1 due later this year).