【发布时间】:2010-12-16 16:16:12
【问题描述】:
我是 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;
}
对应的 Makefile:
all: test.c
gcc -o test test.c
./test &
top -p `pidof ./test`
killall ./test
【问题讨论】:
-
您是否使用过挡泥板对其进行了测试?还是瓦尔格林?它们将为您提供更好的内存泄漏统计信息。
-
你知道你要分配多少内存吗?
-
谁在乎?这是一个 64 位系统——地址空间并不完全是稀缺资源。无论如何,系统从来没有给你对物理内存 (RAM) 的独占控制权。
标签: c++ c memory-management malloc free