I am trying to learn more about how memory is handled in C++, and I have a question about how memory is released when a variable is reassigned. To monitor memory consumption, I have a (Linux-specific) function CheckMem()
which calls pmap
to see how much memory the process is using.
I then simply create a vector of size 1, reassign it to a vector of size one million, then reassign it again to size 1, and observe how the memory changes.
#include <iostream>
#include <vector>
#include <sstream>
#include <cstdio>
#include <unistd.h>
using namespace std;
void CheckMem()
{
char cmdstring[100],outbuf[500],buf[100];
sprintf(cmdstring,"pmap -x %d | tail -1",getpid());
FILE* output = popen(cmdstring,"r");
fgets(outbuf,500,output);
size_t kb,rss,dirty;
istringstream ss(outbuf);
ss >> cmdstring >> buf >> kb >> rss >> dirty;
cout << "RSS: " << rss << " KB" << endl;
}
int main()
{
vector<double> vd(1);
CheckMem();
vd = vector<double>(1000000);
CheckMem();
vd = vector<double>(1);
CheckMem();
return 0;
}
If I compile with g++ (gcc version 4.8.4), I get the following output:
RSS: 1184 KB
RSS: 9128 KB
RSS: 9136 KB
It appears that the memory used for the large vector (1 million doubles ~ 8 MB) is not released when the vector is reassigned to size 1.
However, if I compile with the flag -std=c++11
, then the output changes:
RSS: 1180 KB
RSS: 9112 KB
RSS: 1300 KB
Now the memory appears to be released by the reassignment. Does the C++11 standard somehow treat memory differently for reassignments?