3

At the beginning I use std::map, but I need to force the map to deallocate the memory. I use the map only once and has allocated large memory. The map only returns the memory to heap not to OS, so it still existed.

After some google, I found boost.pool, but I have no clear idea on how to implement a map using it, thanks!

Naszta
  • 7,560
  • 2
  • 33
  • 49
xueyumusic
  • 229
  • 2
  • 9

2 Answers2

0

Try to use swap trick:

std::map<yourtype> store;
...
// release store's memory
store.swap(std::map<yourtype>());

In swap you will create a temporary instance of map object, swap will swap the contents of the temporary instance and the base instance and the temporary instance will be destroyed.

Naszta
  • 7,560
  • 2
  • 33
  • 49
  • Will the swapeed map have the same problem? i.e, return the memory just to heap but not to OS, so still existed... – xueyumusic Feb 09 '12 at 09:11
  • @xueyumusic: you should try it. When you give back memory for heap (`delete` or `free`), you give back memory to the OS. STL objects usually do not free up memory on `clear` and/or on `capacity`. – Naszta Feb 09 '12 at 09:14
  • Answer is only valid in perfect scenario. In real life cases, there are allocations on same pages from _elsewhere_ so pages cannot be returned to OS. Also std::map::clear frees memory. – ST3 Nov 16 '18 at 08:39
-1

What if you write a custom allocator and pass that to the map. Your alocator could use clib's malloc and free. I'm pretty sure that's at the OS level.

Your allocator class only needs to implement the methods shown here: http://www.cplusplus.com/reference/std/memory/allocator/

Then when you define your std::map .. pass the allocator class as the 3rd template argument: http://www.cplusplus.com/reference/stl/map/

eg:

std::map<KeyType, ValueType, less<KeyType>, MyAllocator> 

This link from this book also has some example code for making your own allocator: http://www.josuttis.com/libbook/memory/myalloc.hpp.html

Warning: I think the reason most allocators don't give memory back to the OS is that it's faster to hold on to it for later, than to give back to OS and get more every time; so you might see some speed inefficiencies.

Edit: Also found this neat looking howto: http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4079

matiu
  • 7,469
  • 4
  • 44
  • 48
  • Boost pool does not work out-of-the-box with `std::map`. See http://stackoverflow.com/questions/22951378/how-do-you-determine-the-size-of-the-objects-internally-created-by-a-stdmap – Dan Nissenbaum Apr 09 '14 at 04:09