Jump to content
  • Advertisement
Sign in to follow this  
Prototype

STLport string 'leaking'

This topic is 4847 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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]

Share this post


Link to post
Share on other sites
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!