我想了解在以下情况下 GCC 运行时发生了什么。
我有一个 C++ 程序,它分配许多内存块然后删除它们。令人费解的是 GCC 运行时没有将内存返回给操作系统。相反,它仍然由我的程序保留,我想以防万一我想在不久的将来分配类似的内存块。
下面的程序演示了发生了什么:
#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;
}
我通过运行“ps -e -o vsz,cmd”检查进程在每次暂停时占用的内存量(当它根本不应该占用任何内存时)。
进程在每次暂停时持有的数量如下:
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。
最佳答案
C 库使用的内存分配器根据 block 的大小以多种方式分配内容。释放内存时,页面并不总是返回给操作系统,尤其是在您进行许多小分配时。
内存只能逐页返回给操作系统,不能用于小分配。
如果您真的需要知道,请检查 C 库源代码并检测它等。
在 C++ 中,您可以覆盖容器的分配器来执行您自己的内存管理——然后您可以做任何您想做的事情(例如 mmap/dev/zero 或其他)
关于c++ - 在 C++ 中,即使调用了 delete,进程什么时候会保留分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1259638/