Reed documentation of malloc
(or malloc(3) from Linux man page)
It can fail, and then returns NULL
; and your code should handle that case:
int *arr = malloc((max+1) * sizeof(int));
if (!arr) { perror("malloc arr"); exit(EXIT_FAILURE); };
You could handle the failure in some other ways, but errno is giving the reason. In practice, recovering a malloc
or calloc
failure is quite tricky. In most cases, exiting abruptly like above is the simplest thing to do. In some cases (think of a server program which should run continuously) you can do otherwise (but that is difficult).
Read also about memory overcommitment (a whole system configurable thing or feature, that I personally dislike and disable, because it might make malloc
apparently succeed when memory resources are exhausted; on Linux read about Out-of-memory killer)
See also this (a silly implementation of malloc
)
BTW, you need to be sure that (max+1) * sizeof(int)
is not overflowing, and you'll better define size_t max = 1399469912;
(not int
).
Notice that you are requesting (on systems having sizeof(int)==4
like my Linux/x86-64 desktop) more than five gigabytes. This is a significant amount of virtual address space.