On Linux, with 16 GB of RAM, why would the following segfault:
#include <stdlib.h>
#define N 44000
int main(void) {
long width = N*2 - 1;
int * c = (int *) calloc(width*N, sizeof(int));
c[N/2] = 1;
return 0;
}
According to GDB the problem is from c[N/2] = 1 , but what is the reason?
You’re allocating around 14-15 GB memory, and for whatever reason the allocator cannot
give you that much at the moment- thus
callocreturns NULL and you segfault as you’re dereferencing a NULL pointer.Check if calloc returns NULL.
That’s assuming you’re compiling a 64-bit program under a 64-bit Linux. If you’re doing something else – you might overflow the calculation to the first argument to
callocif a long is not 64 bits on your system.For example, try