Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming, why does this large array declaration produce a segmentation fault?

Tags:

arrays

c

integer

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;

}
like image 749
aoeu Avatar asked Jun 16 '10 00:06

aoeu


People also ask

What is segmentation fault in c array?

A space that is not allocated to you but you try to access it anyway. You cannot get in. In other words, it gives an error. The same way if at any point in a program, memory space that is not allocated to a particular variable or code block is accessed a segmentation fault occurs, also called the core dump error.


2 Answers

Well, for one thing, that's two billion integers. If you have a 32-bit address space and int has 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 using free() when you are done with it!).

like image 158
James McNellis Avatar answered Nov 15 '22 04:11

James McNellis


int  nums_size = 2000000000;

int nums[nums_size];

Does not mean 2000000000 bytes of ints, it means 2000000000 elements of type int, which on a 32-bit platform means that you are consuming almost 8GB of memory - this is impossible.

like image 28
Chris K Avatar answered Nov 15 '22 05:11

Chris K