Take the 2-minute tour ×

I've noticed that when I use an unordered set unordered_set<int> theSet; to hold large number of integers, it doesn't free the memory even with calls to clear() or rehash(0). Even if I defined the set locally in a function, and the function finished execusion, the most of the memory reserved by the set is still reserved. Any ideas?

Below is a sample code, when the tester function returns and we are in main, the memory used by tester is not freed


using namespace std;
using std::tr1::unordered_set;

void tester() {


int main() {
    return 0;
share|improve this question
How are you measuring memory consumption? –  NPE Nov 28 '12 at 18:20
This kind of question should have a code snippet attached to reproduce the behaviour. –  mfontanini Nov 28 '12 at 18:24
I use top on unix –  user1785771 Nov 28 '12 at 18:28
The standard doesn't require that clear or rehash free anything. clear is required to call destructors of all elements and to leave the set in an "empty" state, but that doesn't mean it has to release backing memor. Similar is true for rehashing. Insofar, whether or not this happens, I don't consider it a problem. Popping elements off a vector usually doesn't free anything either. Nobody would consider that problematic. –  Damon Nov 28 '12 at 18:32
top doesn't measure what you think it measures. –  Robᵩ Nov 28 '12 at 18:32
add comment

2 Answers

You can swap with a temporary set.

std::unordered_set<MyType> mySet;

// do stuff with mySet

std::unordered_set<MyType>().swap( mySet );

But your second claim doesn't make any sense. If you've declared a set local to a function, all memory used by that set will be released when the function exits.

share|improve this answer
add comment

I use top on unix

What probably happens is that memory does get released into the heap. However, the heap is not shrunk and the memory is not released back to the OS. Thus top is not showing any reduction in memory consumption.

If you were to re-create the unordered_set after destroying the first one, you probably wouldn't see an increase in memory consumption as measured by top.

When the process terminates, all its resources will be reclaimed.

share|improve this answer
But once the program terminates, the memory immediately drops! –  user1785771 Nov 28 '12 at 18:52
@user1785771: Yes. When the process terminates, all its resources are reclaimed. –  NPE Nov 28 '12 at 18:53
add comment

Your Answer


