In C ++, when does a process save allocated memory, even if delete is called?

I would like to understand what happens in the GCC runtime in the following situation.

I have a C ++ program that allocates many blocks of memory and then deletes them. What is bewildering is that the memory does not return to the OS by the GCC runtime. Instead, it is still supported by my program, I assume that in the near future I will want to allocate similar pieces of memory.

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 stored during each pause (when it should not contain any memory at all) by running "ps -e -o vsz, cmd".

The amount held by the process at each pause is as follows:

  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  

Fedora Core 6 GCC 4.1.1.

+3
2

, C, , . , .

, .

, C ..

++ - , (, mmap/dev/zero - )

+10

, , Linux, malloc , , , - , , , , - .

, , - , , , , , .

, , , , , - . , , .

+4

Source: https://habr.com/ru/post/1714855/


All Articles