Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array crashes with more than 120000 elements [duplicate]

Tags:

c++

arrays

When i do:

vector<double> myVect(120000000, 0);

I can make the vector hold seemingly as many elements as i want. However, when i do:

double myArray[120000];

I am limited to somewhere around 120000-130000 elements before my program crashes. Is there something screwy going on or are arrays really this limited?

like image 986
Rob Allsopp Avatar asked Mar 23 '23 18:03

Rob Allsopp


1 Answers

Arrays are not themselves limited to any fixed size, but arrays that you allocated in the automatic storage (commonly known as "the stack") are limited to the size of the stack. When you allocate large arrays in the static storage, you can make much larger arrays. Same goes for dynamic allocations: whatever the size of the vector that you could allocate without triggering a memory overflow, you can make an array of the same size with the new operator.

For example, you can do this without triggering stack overflow:

static double myArray[120000000]; // static memory area

or this:

double *myArray = new double[120000000]; // dynamic memory area
like image 72
Sergey Kalinichenko Avatar answered Apr 17 '23 08:04

Sergey Kalinichenko