dimanche 7 décembre 2014

C++ STL container memory management in vector


Vote count:

0




I'm coding some mission critical code that I have to make sure it's absolutely free of memory leaks. I've wrote a small function that allows me to retrieve the memory usage at runtime and I make measurements before and after executing some code (that should be leak free) to see if memory usage remains on the same level.


While debugging a piece of code that was 'leaking', I finally found the culprit to be a vector container.


The minimal code that reproduces what I'm seeing is the following:



vector<char*>* v = new vector<char*>();
int n = 1024*1024;
while(n--) v->push_back(new char[256]()); // A
for(vector<char*>::iterator it=v->begin();it!=v->end();++it) delete[] (*it);
delete v;


If you run that code (disabling compiler optimizations of course, -O0) and put some trap at the end so that the program doesn't exit (like cin.ignore();) you would see that your program should be using around 20Mb or so of memory.


I'd like to understand why does that happen. There's a line I marked with A, where if you allocate a larger char array you would see that the 'remaining' memory at the end is larger too. I wouldn't call this a leak per se beause apparently that memory could be reused if I allocate and fill another STL container, but still I would have expected to have that memory completely freed when the code finishes.


Can someone shed some light on to why is this memory still being used? And how may I 'free' it for real?



asked 2 mins ago







C++ STL container memory management in vector

Aucun commentaire:

Enregistrer un commentaire