1

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
user2648841
  • 247
  • 1
  • 4
  • 9

3 Answers3

3

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

When a variable is non-static, it is allocated on stack. With ~4 MB array, you are probably getting stack overflow

Erbureth
  • 3,378
  • 22
  • 39
0

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.

Max
  • 10,701
  • 2
  • 24
  • 48