When I initialise array of 1,000,000 integers, program crashes, but when I put keyword static in front everything works perfectly, why?
int a[1000000] <- crash
static int a[1000000] <- runs correctly
When I initialise array of 1,000,000 integers, program crashes, but when I put keyword static in front everything works perfectly, why?
int a[1000000] <- crash
static int a[1000000] <- runs correctly
The reason is that the first is allocated on the stack, and there is not enough stack space to accommodate it.
The second lives in the data segment.
Since you've tagged the question [c++]
, I'd recommend that you use std::vector
instead of an array.
When a variable is non-static, it is allocated on stack. With ~4 MB array, you are probably getting stack overflow
The first is allocated on the stack, and you've probably overflowed your stack. The second is allocated in global/static memory, which is allocated when your program starts up.
You could also use malloc/free or new/delete so it will be on the heap, but.you need to make sure it was successful.