malloc可以为您的程序分配多少GB

use*_*983 5 c malloc operating-system

我使用以下代码找出它,但我总是得到1作为答案.有什么不对.谢谢

#include <stdio.h>
#include <stdlib.h>

int main(){
    int mult = 0;
    int chk =8;
    do{
        mult+=1;
        int *p = (int*)malloc(1024*1024*1024*mult);
        if(p==0){
            chk =0;

        }else{
            free(p);
        }
    }while(chk !=0);
    mult = mult -1;
    printf("The number of gigs allocated is : %d\n",mult);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

只是为了帮助,我有一个安装了Windows和Linux的64位系统.因此,即使我在64位系统上只获得1 gb的答案,上述逻辑是否正确?

Mar*_*ins 3

如果是 32 位操作系统,那么最大的连续块为 1GB(或介于 2GB 之间)也就不足为奇了。在 64 位操作系统上,更大的块是可能的。

如果您更改代码以分配较小的单个块,则您可能能够分配超过 1GB 的总大小。