C, why does this declaration of a large array create a segmentation error?

This code causes a segmentation error during array declaration. I am confused why this is happening. I intentionally chose 2,000,000,000 as the 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;

}
+5
source share
6 answers

Well, first of all, it's two billion integers. If you have a 32-bit address space and intis 4 bytes in size on your platform (typical for a 32-bit platform), you cannot store this many integers, period.

Even so, you only have so much free space on the stack where the automatic variables are located.

, malloc() ( , , free(), !).

+21
int  nums_size = 2000000000;

int nums[nums_size];

2000000000 ints, 2000000000 int, 32- , 8 - .

+4

. C/++ .

, ( ) malloc 'd.

, , , , , , , segfault.

+3

. ( 1 -8 , ), . - malloc() .

+2

The answer to your question is simple: stackoverflow . No, no, not the site, but the actual process of "stack overflow." You do not have enough stack to store this array. So simple. Doing this on systems with limited memory is sheer madness. Also see this question .

+1
source

This version works fine on my PC:

const int nums_size = 2000000000;
int nums[nums_size];

int main()
{
    int i;
    for(i = 0; i < nums_size; i++) {
        nums[i] = i;
    }

    return 0;
}

(Okay, be honest. It starts fine, but soon turns into a swap.)

0
source

All Articles