0

Something like this throws an error:

using namespace std;


int main()
{
    int test[1000000] = {};
}

Something like this doesn't:

using namespace std;

int test[1000000] = {};

int main()
{
}

Why is that? A million ints isn't even too memory-demanding.

Straightfw
  • 2,143
  • 5
  • 26
  • 39

2 Answers2

5

The first one allocates space on the stack. The second one allocates space in the data segment at compile/link time. The stack is of limited size.

Dale Wilson
  • 9,166
  • 3
  • 34
  • 52
0

Stack is not dynamic, but you can also do this

int* arr = new int[1000000];

but don't forget to delete it because this declares array in the heap which is dynamic memory and by deleting it from heap you prevent the memory leak.

Example :

delete arr;

This is just alternative how to use memory

James
  • 11
  • 4
  • 2
    That's quite beside the question. – Deduplicator Oct 08 '14 at 18:16
  • @Deduplicator I disagree. This allocates the array from the heap instead of the stack, which solves OP's error. – 3Dave Oct 08 '14 at 18:26
  • 1
    @DavidLively Which is exactly why it's besides the point. The question isn't "How do I fix it", but rather "Why does this happen." This in *no way at all* explains why the stack allocation fails. – Borgleader Oct 08 '14 at 18:30