cho*_*zee 1 c memory malloc operating-system
请看一下这段代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* foo = (char*)malloc(500000000);
// when I uncomment stuff that's below then operating system
// admits that this program uses 500MB of memory. If I keep
// this commented, it claims that the program uses almost no
// memory at all. Why is it so?
/*
for (int i=0; i<500000000; i++)
{
foo[i] = (char)i;
}
*/
int bar; scanf("%d", &bar); // wait so I can see what's goin on
free(foo);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的直觉很简单.当我使用malloc调用分配500MB时,OS应该说该进程正在使用超过500MB的内存.但显然,它不会那样工作.我错过了什么?操作系统使用的技巧是什么,我应该阅读什么?
提前感谢您提供任何线索.
我错过了什么?操作系统使用的技巧是什么,我应该阅读什么
这是一种懒惰分配形式.简而言之:
malloc 要求操作系统提供大量内存,操作系统会:"确定,这里你去"并且(几乎)没有这种情况发生在每页.因此,如果您的系统中的页面大小for增加i(可能是4096或类似的东西),您将获得相同的用法.作为一个简单的技巧,尝试玩for触摸元素的数量.作为奖励,尝试通过将大小除以页面大小来预测内存使用情况