C中的堆大小限制
我对C程序的程序执行布局图中的堆有疑问。
我知道所有动态分配的内存都被分配到动态增长的堆中。 但是我想知道C程序的最大堆大小是多少?
我只是附加一个示例C程序...在这里,我试图分配1GB的内存字符串,甚至做memset ...
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *temp;
mybuffer=malloc(1024*1024*1024*1);
temp = memset(mybuffer,0,(1024*1024*1024*1));
if( (mybuffer == temp) && (mybuffer != NULL))
printf("%x - %xn", mybuffer, &mybuffer[((1024*1024*1024*1)-1)]]);
else
printf("Wrongn");
sleep(20);
free(mybuffer);
return 0;
}
如果我一次运行3个实例中的程序,那么malloc应该至少在一个实例中失败[我觉得] ...但仍然malloc是成功的。
如果成功,我可以知道操作系统如何照顾3GB动态分配的内存。
你的机器很可能在RAM上过度使用,在你真正写入之前不使用内存。 尝试在分配它之后写入每个块,从而迫使操作系统确保将真实RAM映射到返回的malloc()
地址。
从linux malloc页面,
BUGS
By default, Linux follows an optimistic memory allocation strategy.
This means that when malloc() returns non-NULL there is no guarantee
that the memory really is available. This is a really bad bug. In
case it turns out that the system is out of memory, one or more pro‐
cesses will be killed by the infamous OOM killer. In case Linux is
employed under circumstances where it would be less desirable to sud‐
denly lose some randomly picked processes, and moreover the kernel ver‐
sion is sufficiently recent, one can switch off this overcommitting
behavior using a command like:
# echo 2 > /proc/sys/vm/overcommit_memory
See also the kernel Documentation directory, files vm/overcommit-
accounting and sysctl/vm.txt.
你混淆了物理内存和虚拟内存。
http://apollo.lsc.vsc.edu/metadmin/references/sag/x1752.html
http://en.wikipedia.org/wiki/Virtual_memory
http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory
链接地址: http://www.djcxy.com/p/86505.html