Questions / Quant development, C++ ownership & memory

Vector growth changes addresses

Applied, about 6 minutes. Question D013.

v.capacity() is exactly 3 before the push_back. Afterward, how many of the three original elements can still be read through p?

std::vector<int> v{1, 2, 3};
int* p = v.data();
v.push_back(4);

Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.

Show the answer and worked solution

Answer: 0 elements

  1. Appending a fourth element exceeds capacity 3, so the vector reallocates.
  2. Reallocation moves every element to new storage and frees the old block.
  3. p points into the freed block, so none of the elements can be read through it.

Interview shortcut. Growth past capacity reallocates: all old pointers dangle.

Takeaway. Reallocation invalidates every pointer into the vector.

In the app this has a follow-up where one thing about the setup changes. Try the follow-up.

More c++ ownership & memory questions