C中的堆大小限制

cod*_*eak 3 c linux heap

我对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 - %x\n", mybuffer, &mybuffer[((1024*1024*1024*1)-1)]]);
       else
       printf("Wrong\n");

       sleep(20);
       free(mybuffer);
       return 0;
    }
Run Code Online (Sandbox Code Playgroud)

如果我一次在3个实例中运行上面的程序,那么malloc应该至少在一个实例中失败[我感觉如此] ......但仍然是malloc成功的.

如果成功,我可以知道操作系统如何处理3GB的动态分配内存.

unw*_*ind 8

你的机器很可能overcomitting的RAM,并且不使用内存,直到你真正写.尝试在分配后写入每个块,从而强制操作系统确保将实际RAM映射到malloc()返回的地址.


lor*_*zog 7

从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.
Run Code Online (Sandbox Code Playgroud)