Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault due to lack of memory in C

This code gives me segmentation fault about 1/2 of the time:

int main(int argc, char **argv) {
    float test[2619560];
    int i;
    for(i = 0; i < 2619560; i++)
        test[i] = 1.0f;
}

I actually need to allocate a much larger array, is there some way of allowing the operating system to allow me get more memory?

I am using Linux Ubuntu 9.10

like image 808
Tom Avatar asked Nov 19 '10 00:11

Tom


1 Answers

You are overflowing the default maximum stack size, which is 8 MB.

You can either increase the stack size - eg. for 32 MB:

ulimit -s 32767

... or you can switch to allocation with malloc:

float *test = malloc(2619560 * sizeof test[0]);
like image 170
caf Avatar answered Oct 05 '22 01:10

caf