STLport string 'leaking'

Started by
2 comments, last by Prototype 19 years, 2 months ago
I've encountered some strange behaviour from STLport's std::string implementation. Consider the following code (run through debugger):

  #include <crtdbg.h>
  #include <string>

  void DoStuff() {
      std::string S("foobar");
  }

  int main() {
      _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
      DoStuff();
      return 0;
  }
You would expect the memory used by S be freed when DoStuff() returns but Windows reports a memory leak here (320 bytes on my machine). However, if the length of S is set to >127 the memory leak is not reported (try std::string S(200, ' ')). I suspect STLport keeps a separate pool for short strings which is only released when the program terminates, but that's just a guess. Any explanations or workarounds are appreciated. I'm using VC6 with STLport 4.6.2.
Advertisement
It's very possible... the STLPort source code is entirely available, so that's the best place to start looking for explanations. RTFS. [grin]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Not 100% sure, but I believe this is due to the way that STLport uses a page system for small memory allocation by default.

All allocations of <=128 bytes are allocated on pages of the same sized objects in mulitples of 16, so there are pages for allocs of 16, 32, 48, 64, 80, 96, 112 and 128 bytes. Allocation of >128 bytes are passed straight through to the system memory malloc function.

As far as I know, these pages are allocated but never free'd, and slots within the pages are just added or removed from a 'free slot' list.

This gives the illusion that there is a memory leak, when it is actually just keeping the memory 'reserved' for the STL's small allocations.

The code for this page allocator is in _alloc.h and _alloc.c within the 'stlport\stl' directory; but be warned it's not very readable code.

If you want to change this default behaviour (maybe to add memory tracking within the page allocator), then you can do so by using custom allocators for your stl types. There also seem to be some #defines to switch different default allocators (you could try compiling with _STLP_DEBUG_ALLOC defined) but I haven't tried fiddling with these myself.

Hope that helps.

Defining _STLP_DEBUG_ALLOC did the trick.
Thanks for the help.

This topic is closed to new replies.

Advertisement