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
.这不一定会减少堆的虚拟大小,因此可能无法释放与其关联的物理内存.这就是为什么你没有看到物理内存使用量减少的原因.
归档时间: |
|
查看次数: |
1602 次 |
最近记录: |