You're statically allocating an array on the stack, this means that the compiler will write code to reserve that space, and when your main()
is called, it will try to move the stack pointer way out of the available mapped stack area for your program. Touching the stack would then cause a segmentation fault, which is what you see.
You could increase the stack size, but it's not that simple nor portable, and in general allocating such a large array on the stack is bad practice and should be avoided. To handle such a big array, you should dynamically allocate it, using for example malloc()
.
Here's a working example:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
short int *big;
big = malloc(6000000 * sizeof(short int));
if (big == NULL) {
fputs("Failed to allocate memory!\n", stderr);
return 1;
}
// Do whatever...
free(big);
return 0;
}
Also, remember that you cannot use sizeof()
in this case since big
is a dynamically allocated array (sizeof(big)
would yield the size of the pointer, not the real size of the array). This is because sizeof()
is a compile-time operator and can only help you if the size is known at compile time. In this case, it is not, since the space is allocated at runtime.
If you want to know the size of that array, you can simply calculate it with a multiplication:
short int *big;
const size_t big_size = 6000000ULL * sizeof(short int);
printf("Size: %zu\n", big_size);
big = malloc(big_size);
// ...