MiddleDebuggingVery commonNot answered yet
Why does *p dangle after push_back?
This caches a pointer into a vector, then appends to it.
std::vector<int> v{1, 2, 3};
int* p = &v[0];
v.push_back(4); // may reallocate
std::cout << *p;
Find and fix the bug.
push_back can reallocate the vector's storage when it grows past capacity, invalidating p, which now dangles — UB. Pointers, references, and iterators into a vector are invalidated by reallocation. Fix: re-acquire p after the insert, or reserve capacity up front.
- ✗Believing push_back never moves existing elements
- ✗Thinking raw pointers survive vector reallocation while iterators do not
- ✗Forgetting that capacity growth relocates the whole buffer
- →When exactly does
vector::push_backinvalidate references and iterators? - →How does
reservemake a sequence ofpush_backs pointer-stable?