Reputation: 99
Everyone.
I know vector is dynamic allocated, so it is on heap. But i also know that global variables are neither allocated on heap nor stack. So where is the vector located anyway?
Upvotes: 1
Views: 571
Reputation: 5607
The vector itself will be placed in the static data section of your program. This is not the heap.
But when the vector is storing elements it will allocate a buffer for its data. This will be on the heap.
See below for a possible implementation. The vector is on the left - it does not contain any element data. Once it gets a request to store data, it will allocate a buffer for storing the elements of the vector. This buffer can dynamically grow or shrink.
static data | heap
------------------------+---------------------
ptr to start ------> | first element
size | second element
| ...
Upvotes: 1
Reputation: 409266
If you have
std::vector<int> my_global_vector;
defined in the global or namespace scope (i.e. outside any function), then the object is stored in the "data" segment of the program, together with all other (uninitialized) global or namespace variables.
The storage of the object is separate from the storage of the vector data, which is indeed allocated of the heap.
Upvotes: 6