简体   繁体   中英

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?

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, ie 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.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM