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.

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

That's quite beside the question.
@Deduplicator I disagree. This allocates the array from the heap instead of the stack, which solves OP's error.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.