Yasitha Bandara Yasitha Bandara - 3 months ago 11
C Question

Run time error on large array sizes in C/C++

first i don't know how to name this question.

i tried to do this declare array (size=1,000,000) in C++ it give me a run time error.

unsigned long long a[1000000];


but it allows this(size=100,000)

unsigned long long a[100000];


again it give run time error for following

unsigned long long a[100000];
unsigned long long b[100000];


but i can do same thing as follows

unsigned long long* a = new unsigned long long[1000000];


can any one please explain the reason for this.

Answer

In C++, when you're doing this:

unsigned long long a[100000];

It allocates the memory from the stack. Stack memory is limited so you can't do too big allocations.

When you do this:

unsigned long long* a = new unsigned long long[1000000];

It allocates the memory from the heap. Heap allocations can be big.

More information about stack and heap memory is in this Stack Overflow post.

Comments