Declaring a long long array with unsigned int size

Chandan picture Chandan · Dec 19, 2014 · Viewed 9.3k times · Source

I was doing a problem when I encountered a segmentation fault while declaring an array as:

long long ways[max+1];  

where,

unsigned int max = findMax(l,T); // l is an unsigned int array and T is an int.  

and findMax is a function of the type:

unsigned int findMax(unsigned int arr[],int size)  

How can I resolve this?

Answer

Klas Lindbäck picture Klas Lindbäck · Dec 19, 2014

A probable reason is that the array is too big for the stack.

Typical stack sizes as of now is 1-16 Mb (could be considerably less in an embedded system). If long long is 8 bytes it would mean that allocating one array of more than 125000 elements could be problematic. And you also want to leave room for other auto variables.

Really big arrays should not be allocated on the stack.

You could try allocating it in the heap instead:

long long *ways = calloc(max+1, sizeof *ways);
if (ways == NULL) {
    // allocation failed!!
}
// Do stuff.
free(ways);