我在 malloc
调用方面遇到了一个奇怪的问题。我正在开发一个使用巨大数组(大小以 GB 为单位)的程序,并且在尝试使用 malloc 为数组分配内存时,我发现,即使我分配一个大于我的 RAM(64GB)的大小。
参见下面的代码:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define Sixteen_G 16000000000
int main() {
int *c = (int *)malloc(sizeof(int)*Sixteen_G);
int *d = (int *)malloc(sizeof(int)*Sixteen_G);
int *e = (int *)malloc(sizeof(int)*Sixteen_G);
int *f = (int *)malloc(sizeof(int)*Sixteen_G);
int *g = (int *)malloc(sizeof(int)*Sixteen_G);
if(c == NULL)
printf("c Allocation failed\n");
if(d == NULL)
printf("d Allocation failed\n");
if(e == NULL)
printf("e Allocation failed\n");
if(f == NULL)
printf("e Allocation failed\n");
if(g == NULL)
printf("e Allocation failed\n");
else
printf("All arrays allocated\n");
return 0;
}
上述代码的输出是:
All arrays allocated
此外,对 = 17GB
大小的 malloc
的单个调用失败,但对 16GB
的多个调用正在传递。
有人可以解释一下为什么 malloc 能够分配这么多内存,而我的系统 RAM 大小只有 64GB,以及 malloc
在单次/多次调用时究竟如何工作
最佳答案
您可能想要禁用 memory overcommitment .
(我真的不喜欢这个功能)
参见this问题。
您应该编码并 test against malloc
failure .
了解更多关于virtual address space的信息。另请参阅this .
关于c - 为什么我可以分配比 RAM 更大的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47252646/