VS2005 STL strstream and stringstream leaks

Well, it turns out that my initial gut instinct about the leaks that I found in my socket servers when built with VS 2005 was correct. It was an STL thing.

The following code reproduces the problem.

#include <strstream>
#include <sstream>
#include <iostream>
 
#include <stdio.h>
 
using std::strstream;
using std::ostrstream;
using std::stringstream;
using std::ostringstream;
using std::cout;
using std::endl;
 
int main(int argc, char* argv[])
{
   cout << "Ready - press a key to test strsteam" << endl;
 
   getchar();
 
   const size_t loopCount = 100000;
      
   size_t i;
    
   for (i = 0; i < loopCount; ++i)
   {
      strstream buf;
   }
 
   cout << "Ready - press a key to test ostrsteam" << endl;
 
   getchar();
 
   for (i = 0; i < loopCount; ++i)
   {
      ostrstream buf;
   }
 
   cout << "Ready - press a key to test stringsteam" << endl;
 
   getchar();
 
   for (i = 0; i < loopCount; ++i)
   {
      stringstream buf;
   }
 
   cout << "Ready - press a key to test ostringsteam" << endl;
 
   getchar();
 
   for (i = 0; i < loopCount; ++i)
   {
      ostringstream buf;
   }
   
   cout << "Done - press a key" << endl;
   
   getchar();
   
   return 0;
}

The code and projects for VC6 through VS2005 can be downloaded from here.

If you build the test program with VS2005 and run it you’ll see that there’s a memory leak when you create and destroy a strstream or stringstream and not when you create and destroy a ostrstream or ostringstream. If you build with any other compiler and STL combination there’s no leak. If you build with VS2005 and STLPort there’s no leak. I spelunked around the VS2005 iosteams source for a little while but a) it’s fairly gross code, b) I have a work around to my problem, I can use (in fact should use) one of the output only streams and, c) I got bored.

So. The horrible leaks that were reported in the current latest version of the socket server code when built with VS2005 aren’t my problem. You can fix the current code by replacing all instances of strsream with ostrstream (that’s probably just in one place in the implementations of ToString() in utils.h). I will still be posting a new set of code next week some time to address the other VS2005 build issues and to roll in the fix for the well known leak in the ThreadPoolLargePacketEchoServer example.

[Update: 29/03/2007 - this leak was fixed in SP1 of VS2005, as far as I know…]