Strange Memory Leak

closed account (j2v4jE8b)
There is a memory leak after clearing the vector (Base) that i don't understand.
The Task Manager shows an increase of 4 K - once so it doesn't increase further when repeating the routine but I don't get it either.
Could someone please help me with that ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;

class Phenomenon {
 public:
 string Data;
};

vector <Phenomenon*> Base;

void Shutdown() {
 while (Base.size()) {
   delete Base[Base.size()-1];
   Base.pop_back();
   } Base.clear();
}

int main()
{
 string D;
 Phenomenon *T;

     while (getline(cin,D)) {
          for (int i=0; i < 500000; i++) {
             Base.push_back(new Phenomenon());  // TASK MANAGER SHOWS LEAK
             Shutdown();
          }
     cout << "clear";
     }
     	system("pause");
return 0;
}
Last edited on
There's no memory leak in the code you posted.
Regardless, when you have a vector that "owns" the objects the pointers are pointing to, you need to/should use a ptr_vector.

And instead of Base[Base.size()-1] you can write: Base.back();

The Task Manager shows an increase of 4 K - once so it doesn't increase further when repeating the routine but I don't get it either.

These are details of the memory management implementation. Nothing you need to worry about.
When you added an element for the first time to the vector, it internally allocated an array of size 1 - this apparently caused one new page to be allocated (on most systems, a memory page is 4K). Even when you clear a vector it maintains its old capacity.
Last edited on
@ OP: To be clear Athar means your application retains the memory already allocated to it by the OS for that instance, the vector it self does not retain this memory space. Calling the member function "clear()" sets the size of the vector back to zero: http://www.cplusplus.com/reference/stl/vector/clear/
The size is reset and the objects are destructed when calling clear(), but the capacity remains the same.
So the vector keeps an allocation of at least sizeof(T)*capacity.
closed account (j2v4jE8b)
Thanks alot.

>>
the vector keeps an allocation of at least sizeof(T)*capacity
- so the capacity remains the at maximum of what was reserved once until the vector is destructed ? Is it the same for other container types ?
so the capacity remains the at maximum of what was reserved once until the vector is destructed ?

Yes.

Is it the same for other container types ?

Not really, since the other STL containers (except for std::string) don't even have the concept of capacity.
Last edited on
Topic archived. No new replies allowed.