I would like to understand what is going on in the GCC runtime in the following situation.
I have a C++ program that allocates many blocks of memory and then deletes them. What's puzzling is that the memory is not being returned to the OS by the GCC runtime. Instead, it is still being kept by my program, I assume in case I want to allocate similar chunks of memory in the near future.
The following program demonstrates what happens:
#include <iostream>
using namespace std;
void pause1()
{
cout << "press any key and enter to continue";
char ch;
cin >> ch;
}
void allocate(int size)
{
int **array = new int*[size];
for (int c = 0; c < size; c++) {
array[c] = new int;
}
cout << "after allocation of " << size << endl;
for (int c = 0; c < size; c++) {
delete array[c];
}
delete [] array;
}
int main() {
cout << "at start" << endl;
pause1();
int size = 1000000;
for (int i = 0; i < 3; i++) {
allocate(size);
cout << "after free" << endl;
pause1();
size *= 2;
}
return 0;
}
I check the amount of memory held by the process at each pause (when it should not be holding any memory at all) by running "ps -e -o vsz,cmd".
The amount held by the process at each pause is the following:
2648kb - at start 18356kb - after allocating and freeing 1,000,000 ints 2780kb - after allocating and freeing 2,000,000 ints 65216kb - after allocating and freeing 4,000,000 ints
I'm running on Fedora Core 6 and using GCC 4.1.1.