Search code examples
c++vectorgetrusage

C++ Object allocation and deallocation


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**

Solution

  • I'm not up on the specifics of getrusage but from a quick google, it seems to be reports OS resources used. Typically, the C++ Run-time library which manages the memory used by malloc/new will request a large block of memory from the OS when it needs it, make malloc requests out of that block, and then hold onto the block even after all the allocations are freed, so it has some avaiable to handle the next request without having to ask the OS again.