Ravin Sher
2 min readJan 13, 2021

What happens to a C++ vector when the memory capacity of a vector is smaller than requested. Describe the sequence of the activities done inside the vector

When the memory capacity of the vector is smaller than requested a new memory block is allocated to vector and all previous elements will be moved into the new one. (Remember here, vector data is copied to new location and the the vector itself).There addresses will also change.
Vector on Stack:

As we can see heap is empty and nothing happens on there but variables occupies thre memory that is necessary for all of its members on stack. Vect1 just sits there and wait to get destroyed.
A vector on the heap:
Now first we need a pointer to a vector to create a vector using dynamic heap allocation.

Now our vp variable is on stack and our vector is on heap.Vector will not move to heap becuase its size is constant. Only the pointers will move to follow the data position in memory if a reallocation takes place.
Lets add the elements to vector using something like push_back.

The variable vect1 is still where it has been but memory on the heap was allocated to contain one element .
Now here is the real part when we add another element ,
1.Space allocated on the heap for the data elements is not enough
2.A new memory block will be allocated for both elements.
3.First element will be copied/moved to new storage.
4.Old memory will be deallocated.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response