这是一个后续我刚才问的问题在这里.
我创建了一个简单的程序来帮助自己理解的内存分配,malloc()和free().注意注释掉的free行.我创建了一个故意的内存泄漏,所以我可以看到Windows报告"Mem Usage"膨胀到1GB.但后来我发现了一些奇怪的东西.如果我在自由行的正上方注释掉循环,那么我没有用随机整数初始化我的存储块,看起来该空间实际上并没有被程序从操作系统"声明".为什么是这样?
当然,我还没有对它进行初始化,但我声称它,所以操作系统不应该看到该程序使用1GB,无论该GB是否已初始化?
#include <stdio.h>
#include <stdlib.h>
void alloc_one_meg() {
int *pmeg = (int *) malloc(250000*sizeof(int));
int *p = pmeg;
int i;
// for (i=0; i<250000; i++) /* removing this loop causes memory to not be used? */
// *p++ = rand();
// free((void *)pmeg); /* removing this line causes memory leak! */
}
main()
{
int i;
for (i=0; i<1000; i++) {
alloc_one_meg();
}
}
Run Code Online (Sandbox Code Playgroud)
分配的内存可以在两种状态在Windows:保留,并COMMITED(见的文档VirtualAlloc约MEM_RESERVE:"Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging file on disk.").
如果您分配内存但不使用它,它将保持在保留状态,并且操作系统不会将其计为已用内存.当你尝试使用它时(无论是在写入时,还是在读写时,我都不知道,你可能想要做一个测试来查找),它会变成Commited内存,并且操作系统将其视为用过的.
此外,通过分配的内存malloc会不会是全0(实际上它可能碰巧,但它不能保证)的,因为你还没有初始化它.