Sign in to follow this  
Prototype

STLport string 'leaking'

Recommended Posts

Prototype    2014
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.

Share this post


Link to post
Share on other sites
Fruny    1658
It's very possible... the STLPort source code is entirely available, so that's the best place to start looking for explanations. RTFS. [grin]

Share this post


Link to post
Share on other sites
WillC    548
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this