3

I have a program:

#include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <stdarg.h>
#include <stdio.h>
#include <unistd.h>
using namespace std;

int main() {
    map<int, string> m;

    for (int i = 0; i < 1000000; i++)
    {
        m[i] = "jahsdghsagdfv sahgvsahgd fvsahgdf fsdfjsadvhjgsd jhgfhsahfvsafh asfvasgfv jhgfdvsahgvfs";
    }
    m.clear();
    while (1) {sleep(5);}
    return 1;
}

clear() does nothing. In memory monitor I see memory usage 184 Mb and nothing change after clear. Why ? How to clear memory of map ?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
mitch
  • 2,235
  • 3
  • 27
  • 46
  • 1
    What memory monitor are you using? And what do you mean it does nothing? It removes all the elements from the map. – Marius Bancila Mar 12 '14 at 11:38
  • 7
    There are many duplicates of this, but the answer is that the memory is (or *may* be) released by the `map` but still mapped to your process in case it needs to allocate memory again. Sort of an optimization. If another process needs more memory it might take the free memory from your process. – Some programmer dude Mar 12 '14 at 11:39
  • 4
    Everything is fine. The interaction between your platform and your program isn't what you think. – Kerrek SB Mar 12 '14 at 11:39
  • I know there are many topics about this but I can't find right and clear answer. – mitch Mar 12 '14 at 11:42
  • If you absolutely want to control the exact amount of memory your process is consuming you cannot use a memory allocator (new / malloc) since you depend on his algorithm, see `man sbrk`, but i'm pretty sure your final conclusion will be "okay the current behaviour is fine" when you'll understand what you will need to do to achieve what you seem to want :) – Drax Mar 12 '14 at 17:29
  • I'm super confused as to why I was able to close as a duplicate by myself, doesn't it take 5 people? – Mooing Duck May 17 '14 at 00:15
  • @MooingDuck: Read the bulletins linked at the top of this very page. Or hover over the gold icon next to your name in the close banner. Or just do any research at all, really! http://meta.stackoverflow.com/questions/254589/when-did-i-get-close-vote-superpowers?cb=1 – Lightness Races in Orbit May 17 '14 at 00:33

1 Answers1

1

Yes, map::clear does something: "Removes all elements from the map container (which are destroyed), leaving the container with a size of 0." The data will not be removed also from stack/heap,but this shall not influence you since you'll have no pointer and no cast type to that obsolete data. Probably when you will refill the map that memory area will be reused and updated with new values (if it was not used by other variables meanwhile).

bucur
  • 26
  • 2