#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
long *safeCalloc(int size)
{
long *ptr = calloc(sizeof(long), size);
if (ptr == NULL)
{
printf("Error: memory allocation failed\n");
exit(-1);
}
return ptr;
}
int main(int argc, char *argv[])
{
long lim = 10000000000;
long *x = safeCalloc(lim);
printf("%ld\n", x[0]); //Prints 0
printf("%ld\n", x[50]); //Prints 0
printf("%ld\n", x[lim / 10]); //Prints 0
printf("%ld\n", x[lim / 5]); //Segmentation fault
printf("%ld\n", x[lim - 1]); //Would be a segmentation fault
free(x);
return 0;
}
When running this code I get a segmentation fault when trying to access certain indexes of my array. The array didn't return a null pointer, and I can access several elements without any issues, but when trying to access something with an index bigger than lim / 9. It gives a segmentation fault. I also don't get a segmentation fault if my lim is smaller, for instance 10^9.
I am inclined to think this means I'm out of memory, but shouldn't calloc return NULL if there isn't enough memory?
Does anyone know what I'm doing wrong?