Search code examples
cwindowsmsvcrt

Why does a C program crash if a large variable is declared?


I have the following C program compiled in Microsoft Visual Studio Express 2012:

int main() {
   int a[300000];
   return 0;
}

This crashes with a stack overflow in msvcr110d.dll!__crtFlsGetValue().

If I change the array size from 300,000 to 200,000 it works fine (in so much as this simple program can be said to 'work' since it doesn't do anything).

I'm running on Windows 7 and have also tried this with gcc under Cygwin and it produces the same behaviour (in this case a seg fault).

What the heck?


Solution

  • Because it's being allocated on the stack and the stack has a limited size, obviously not large enough to hold 300000 ints.

    Use heap allocation a la malloc:

    int* a = malloc(sizeof(int) * 300000);
    // ...
    free(a);
    

    The heap can hold a lot more than the stack.