c++ - Visual C++ 运行时 malloc/free 会将内存返回给操作系统吗?

标签 c++ c visual-studio visual-studio-2010 memory-management

问题与 Will malloc implementations return free-ed memory back to the system? 非常相似,但我对 Windows/Microsoft Visual Studio 的答案以及有关确切虚拟内存状态的详细信息感兴趣。

请问Visual C++ CRT free将内存还给系统?关于虚拟内存分配,内存的确切状态是什么?对一个大内存块做free之后, block 中的内存是committed,reserved,还是free?如果我调用_heapmin怎么办?免费后?

最佳答案

查看2010的源码,可以看到malloc/free call HeapAlloc/HeapFree Win32 API 直接运行,使用 _crtheap 作为运行时创建的堆。因此,VS 2010 和最近的 Windows 版本(Win2000、WinXP、Vista、Win 7)的答案是:

free 返回的内存返回给 OS,但它保持提交状态。

Heap Functions documentation关于如何处理内存 promise 的说明如下:

The HeapCreate function creates a private heap object from which the calling process can allocate memory blocks by using the HeapAlloc function. ... Additional pages are automatically committed from this reserved space if requests by HeapAlloc exceed the current size of committed pages, assuming that the physical storage for it is available. Once the pages are committed, they are not decommitted until the process is terminated or until the heap is destroyed by calling the HeapDestroy function.

此外,HeapCreate documentation关于没有设置最大大小的堆的情况如下:

If dwMaximumSize is 0, the heap can grow in size. The heap's size is limited only by the available memory. Requests to allocate memory blocks larger than the limit for a fixed-size heap do not automatically fail; instead, the system calls the VirtualAlloc function to obtain the memory that is needed for large blocks. Applications that need to allocate large memory blocks should set dwMaximumSize to 0.

我没有发现任何可以说明使用 VirtualAlloc 分配的 block 在发布时是否以特殊方式处理的信息,可能需要进行实验才能知道这一点。

至于_heapmin ,VS 2010 什么都不做,因为它只调用 HeapCompact并且 CRT 堆没有关闭自动合并。因此,_heapmin 的文档似乎是错误的,很可能是某个旧版本运行时的遗留物。

关于c++ - Visual C++ 运行时 malloc/free 会将内存返回给操作系统吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6493299/

相关文章:

c++ - I2C-dev : Change write and read parameters

C++ 线程和变量

c++ - 处理 POSIX 套接字 read() 错误

c - 使用指针访问 typedef 结构

visual-studio - 我应该抑制 CA1062 : Validate arguments of public methods?

c++ - 在派生类上应用父类(super class)测试

c - 我将如何着手用 C 编写解释器?

在 C 问题中将字符串转换为 float ?

entity-framework - 如何在 Entity Framework 中添加外键关系?

css - 有什么方法可以让字体的颜色在 css 中有值(value)?