The following program produces a segmentation error, and I'm not sure why. mallocsucceeds, so it doesn't seem to be an initialization error, but for some reason it segfaults when I access element 253900. The array is only 4 * 1e6 bytes or about a megabyte.
This gives a lot of output.
#include <stdlib.h>
#include <stdio.h>
int *long_array(size_t N) {
int *arr = (int *) malloc(N);
if (arr == NULL) { printf("could not malloc"); exit(1); }
for (size_t i = 0; i < N; i++) {
printf(".. %ld ", i);
arr[i] = 10;
}
printf("done with loop\n");
return arr;
}
int main(void) {
int *arr = long_array(1000000);
printf("%d", arr[5050]);
return 0;
}
I compile this with gcc -std=c99and run the output to see the last few numbers printed before segfault:
253899 .. 253900 .. 2
segmentation fault (core dumped) ./a.out
I do not understand why accessing a specific index causes a segmentation error. I can guess that I should access a memory location outside the address space of my processes, but this seems like an error if I successfully allocated memory from my address space.