Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating large arrays in C

Tags:

arrays

c

My question is related to C language. I have to create a big array of around two million elements but the computer gives a "Segmentation fault (Core dumped)" error. I am simply saying:

int integer_array[2000000];
float float_array[2000000];

I am sure this has something to do with the memory allocated to arrays but I cannot figure out the right solution.

like image 889
Harris Avatar asked Mar 25 '17 10:03

Harris


1 Answers

Usually you need to create such an array dynamically on the heap.

int *integer_array = (int*)malloc(2000000 * sizeof(int));
float *float_array = (float*)malloc(2000000 * sizeof(float));

The array might be too large for stack allocation, e.g. if used not globally, but inside a function.

int main () {
    int a[200000000]; /* => SEGV */
    a[0]=0;
}

The easiest fix, move the array outside:

int a[200000000];
int main () {
    a[0]=0;
}

You can also declare it static:

int main () {
    static int a[200000000];
    a[0]=0;
}

Note that the stack size is system dependent. One can change it with ulimit.

like image 59
rurban Avatar answered Nov 05 '22 09:11

rurban