RTS
RTS

Reputation: 67

C++ vector memory allocation

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?

Upvotes: 0

Views: 1034

Answers (1)

Hanjoung Lee
Hanjoung Lee

Reputation: 2152

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

Upvotes: 6

Related Questions