Questions / Quant development, C++ ownership & memory
Vector growth changes addresses
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
- Appending a fourth element exceeds capacity 3, so the vector reallocates.
- Reallocation moves every element to new storage and frees the old block.
- 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.