I am facing a weird issue with malloc
calls. I am working on a program that uses huge arrays (sizes in GBs) and while trying to allocate memory for the array using malloc
I find that, malloc
is successful even when I allocate a size that is bigger than my RAM (which is 64GB).
See code below:
#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;
}
The output for the above code is:
All arrays allocated
Also a single call to malloc
of size >= 17GB
is failing, but multiple calls to 16GB
are passing.
Can someone explain why malloc is able to allocate that much memory, when my system RAM size is just 64GB, and also how exactly malloc
works on single/multiple calls