0

You can't have:

int array[1000000];

but you can make a vector and store those 1000000 elements.

Is this because the array is stored on the stack and it will not have enough space to grow?

What happens when you use the vector instead?

How does it prevent the issue of storing too many elements?

Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
RTS
  • 57
  • 4
  • 1
    "*can't have int array[1000000]*" Why not? For a static/global variable you are only limited by the available memory. For a local/stack variable you may need to take additional precautions to accommodate such big arrays, but that doesn't mean "*you can't*". – dxiv Feb 10 '21 at 03:55

1 Answers1

6

As defining those as global or in other places might not go in the stack, I assume we are defining int array[1000000] or std::vector<int> array(1000000) in a function definition, i.e. local variables.

For the former, yes you're right. It is stored in the stack and due to stack space limitation, in most environment it is dangerous.

On the other hand, in most of standard library implementations, the latter only contains a size, capacity and pointer where the data is actually stored. So it would take up just a couple dozen bytes in the stack, no matter how many elements are in the vector. And the pointer is generated from heap memory allocation(new or malloc), not the stack.

Here is an example of how many bytes it takes up in the stack for each.

And here is a rough visualization.

enter image description here

Hanjoung Lee
  • 2,123
  • 1
  • 12
  • 20
  • Can the heap memory run out?Here, geeksforgeeks.org/memory-layout-of-c-program, the heap grows toward the stack, why does storing the data in the heap help? Is it because the heap can grow but the stack can't? – RTS Feb 10 '21 at 15:12
  • Heap memory can run out too, since heap and stack are logical areas of a finite memory space. However usually stack memory is a few megabytes, while heap is a few or more gigabytes. – Hanjoung Lee Feb 10 '21 at 17:19
  • More importantly, heap is used to allocate **dynamic memory**. For example, a vector could resize. Say you want to resize the array to 2000000. As Stack does static memory allocation(every function knows its stack size at compilation time) you can't resize of an object on Stack. But if it was on Heap you can freely free the data and allocate a new space with the new size. You may also read https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/ – Hanjoung Lee Feb 10 '21 at 17:21