为什么free()不会真正释放内存?

Ped*_*ves 3 c malloc free

我正在做一些分配和释放内存的测试.这是我正在使用的代码:

#include <stdlib.h>
#include <stdio.h>

#define WAVE_SIZE 100000000

int main(int argc,char* argv[]){

    int i;
    int **p;

    printf("%d allocs...\n",WAVE_SIZE);

    // Malloc
    printf("Allocating memory...\n");
    p = (int**)malloc(WAVE_SIZE*sizeof(int*));
    for(i = 0;i < WAVE_SIZE;i++)
            p[i] = (int*)malloc(sizeof(int));

    // Break
    printf("Press a key to continue...\n");
    scanf("%*s");

    // Dealloc
    printf("Deallocating memory...\n");
    for(i = 0;i < WAVE_SIZE;i++)
            free(p[i]);             
    free(p);

    // Break
    printf("Press a key to continue...\n");
    scanf("%*s");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在休息期间,我检查过程使用的总内存,我看不到我的期望.

直到第一次暂停,我看到内存消耗增加.但是,在第二次暂停时我没有看到它被释放.

这是OS的事吗?如果我的机器负载很高,我没有空闲内存而另一个进程尝试分配会发生什么?

md5*_*md5 8

free不一定将内存释放回操作系统.大多数情况下,它只是将内存区域放回到空闲块列表中.这些空闲块可以重复用于下次调用malloc.


Som*_*ude 5

当分配内存并稍后释放时,该内存仍然保留在进程中但被标记为空闲,因此可以再次分配.这是因为,否则操作系统有可能改变的过程中每次调用时的虚拟内存映射malloc或者free,这需要时间.