Following program creates Objects in one loop and store the reference in vector for future deletion.
I am seeing an unusual behavior, even though the objects are deleting in the second iteration, the getrusage gives a resident memory higher compared to object creation.
Execution environment is in Linux Kernel 3.2.0-49-generic.
#include <iostream>
#include <vector>
#include <stdio.h>
#include <mcheck.h>
#include <sys/time.h>
#include <sys/resource.h>
using namespace std;
void printUsage(string tag)
{
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
printf("%s -- Max RSS - %ld\n", tag.c_str() ,usage.ru_maxrss);
}
class MyObject
{
public:
char array[1024 * 1024];
MyObject() {};
~MyObject() {};
};
int main()
{
printUsage("Starting");
vector<MyObject *> *v = new vector<MyObject *>();
for(int i = 0; i < 10000; i++)
{
MyObject * h = new MyObject();
v->push_back(h);
// The max resident value is same. usual behavior.
// delete h;
}
printUsage("After Object creation");
for(size_t i = 0; i < v->size(); i++)
{
MyObject * h = v->at(i);
delete h;
}
v->clear();
delete v;
printUsage("After Object deletion");
return 0;
}
g++ test/test.cpp -Wall -O2 -g
Output
Starting -- Max RSS - 3060
After Object creation -- Max RSS - 41192
**After Object deletion -- Max RSS - 41380**