似乎在malloc()和free()之后仍然分配了一些内存

Fil*_*yen 4 c c++ malloc free memory-management

我是C的新手.我正在尝试使用malloc + free.我编写了以下测试但由于某种原因,内存未完全释放(顶部仍表示分配给处理的内存大约150MB).这是为什么?

#include <stdio.h>
#include <malloc.h>

typedef struct {
    char *inner;
} structure;

int main()
{
    int i;
    structure** structureArray;

    structureArray = (structure**)malloc(sizeof(structure*)*1000*10000);
    for (i = 0; i < 1000*10000;i++)
    {
        structureArray[i] = (structure*) malloc(sizeof(structure));
        structureArray[i]->inner = (char*) malloc(sizeof(char)*1000*1000*1000);
    }

    printf("freeing memory");
    for (i = 0; i < 1000*10000;i++)
    {
        free(structureArray[i]->inner);
        free(structureArray[i]);
    }
    free(structureArray);

    system("sleep 100");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

相应的Makefile:

all: test.c
    gcc -o test test.c
    ./test &
    top -p `pidof ./test`
    killall ./test
Run Code Online (Sandbox Code Playgroud)

Jay*_*rod 11

top将告诉您分配给您的进程的物理内存量.虚拟内存是物理内存之上的抽象,并且malloc/ free提供了一个抽象.

malloc从程序堆中预留空间.堆只是程序的虚拟地址空间用于临时存储的区域.当您调用malloc更多时,使用brk系统调用扩展堆.但是,尽管堆的虚拟大小增加,但在读取或写入新分配的内存之前,实际上并未分配物理内存.例如,由于您从不写入分配给inner记录字段的内存,因此这些分配不会占用任何物理RAM.

free只是释放由分配的堆的部分malloc.这不一定会减少堆的虚拟大小,因此可能无法释放与其关联的物理内存.这就是为什么你没有看到物理内存使用量减少的原因.


Rom*_*nko 6

Unix内存管理是懒惰的,除非有人真的不需要它,否则不能保证释放进程内存.这是好文章.

另外我建议你检查malloc()结果,你肯定发现它们中至少有一些失败了.