This code produces a segmentation fault during the array declaration. I’m confused as to why this happens. I intentionally selected 2000000000 as a value because it is below 2^31 and can fit into an integer variable.
int main()
{
int nums_size = 2000000000;
int nums[nums_size];
int i;
for(i = 0; i < nums_size; i++) {
nums[i] = i;
}
return 0;
}
Well, for one thing, that’s two billion integers. If you have a 32-bit address space and
inthas a size of four bytes on your platform (typical for a 32-bit platform), you can’t store that many integers, period.Even still, you only have so much space available to you on the stack, which is where automatic variables are located.
If you need a really large array, you should dyncamically allocate it using
malloc()(and if you do so, be sure to free it usingfree()when you are done with it!).