c++ - 在 C++ 中,即使调用了 delete,进程什么时候会保留分配的内存?

标签 c++ memory gcc memory-management

我想了解在以下情况下 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/

相关文章:

c++ - 赋值中的表达式评估

c++ - 通过引用返回没有用吗?

c - 如何在 Linux 上使用另一个 libC 进行编译? (海湾合作委员会)

c - 程序可以在 Dev-C++ 上运行,但不能在 GCC 上运行

android - 为 Android 交叉编译时链接到 libgcc.a 时出错,但符号存在?

c++ - 对整个项目使用 Poco::Logger

c++ - 如何在不关闭正在运行的程序的情况下平滑重启c++程序?

c++ - delete(Object) 是否等同于调用 Object.~Object()

linux kmalloc 在 slab 中超过 8192

java - GridView内存不足位图