Consider the following code, compiled with g++ problem.cpp -o problem:
#include <vector>
using namespace std;
int main()
{
while(1){}
return 0;
}
When this code is executed, the command top reports that ~80K of memory is being consumed.
Now consider this code:
#include <vector>
using namespace std;
int main()
{
vector<int> testVec;
for(int i = 0;i<100000000;i++)testVec.push_back(i);
while(1){}
return 0;
}
As expected, top report that around ~300MB of memory is consumed.
Now finally, consider this code:
#include <vector>
using namespace std;
int main()
{
vector<int> testVec;
for(int i = 0;i<100000000;i++)testVec.push_back(i);
testVec.clear();
vector<int>().swap(testVec);
while(1){}
return 0;
}
Now top reports that ~4196K is being consumed(!) — why isn’t it only ~80K is as in the first example? How can I finally free up that last bit of memory that is presumably being consumed by the vector? I’ve read that in addition to .clear(), the ‘swap trick’ is meant to free up everything but apparently it’s not working as I expected it would do. What am I missing?
You should probably just ignore it. The
swaptrick frees the memory from the vector, but that does not mean that the allocator (or even themallocor equivalent implementation underneath) will yield the memory back to the system. That is, the vector is most probably not the one holding the memory up.