How do I force my std::map to deallocate memory used?

16,415

Solution 1

That behaviour is normal, the runtime library keeps that memory allocated by the map class avaiable to the process so that the next time it needs to allocate memory it does not have to go to the operating system. It is an run time library optimisation.

Solution 2

If you create the map on the heap (via new), deleting it will free up any memory it used.

Share:
16,415

Related videos on Youtube

monkeyking
Author by

monkeyking

Updated on April 19, 2022

Comments

  • monkeyking
    monkeyking about 2 years

    I'm using a std::map, and I can't seem to free the memory back to the OS. It looks like,

    int main(){
      aMap m;
    
      while(keepGoing){
        while(fillUpMap){
           //populate m
        }
        doWhatIwantWithMap(m);
        m.clear();//doesnt free memory back to OS
    
        //flush some buffered values into map for next iteration
        flushIntoMap(m);
      }
    }
    

    Each (fillUpmap) allocates around 1gig, so I'm very much interested in getting this back to my system before it eats up all my memory.

    Ive experienced the same with std::vector, but there I could force it to free by doing a swap with an empty std::vector. This doesn't work with map.

    When I use valgrind it says that all memory is freed, so its not a problem with a leak, since everything is cleared up nicely after a run.

    edit:

    The flush has to appear after the clear.

    • MSalters
      MSalters about 14 years
      Note that your OS probably allocates address space when you try to allocate memory, but only allocates real, physical RAM when you touch the memory. And if you no longer use that RAM but other programs need it, its contents will be swapped out to disk. As a result freeing memory actually frees RAM.