Array index limit in C
arrays, c
Solution
You're allocating around 14-15 GB memory, and for whatever reason the allocator cannot give you that much at the moment- thus `calloc` returns 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 `calloc` if a long is not 64 bits on your system.
For example, try
#include <stdlib.h>
#include <stdio.h>
#define N 44000L
int main(void)
{
size_t width = N * 2 - 1;
printf("Longs are %lu bytes. About to allocate %lu bytes\n",
sizeof(long), width * N * sizeof(int));
int *c = calloc(width * N, sizeof(int));
if (c == NULL) {
perror("calloc");
return 1;
}
c[N / 2] = 1;
return 0;
}
Problem
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?