🪤Go deeper — read the bookC++ Gotchas & Trick Questions— runnable code & full walkthrough →

stl · high

Iterator Invalidation

Why an iterator into a vector dangles after a reallocation, and how reserve / indices / erase's return value avoid it.

🔑 Key line

Reallocation (push_back/insert/resize past capacity) invalidates vector iterators, pointers & refs; erase invalidates from that point on.

The code

std::vector<int> v = {10, 20, 30, 40};
auto it = v.begin() + 1; // points at 20
v.push_back(50); // may REALLOCATE -> it dangles!
// *it; // undefined behavior if reallocated
v.reserve(8); // fix A: pre-allocate, no realloc
size_t i = 1; // fix B: an index survives realloc
it = v.erase(it); // erase returns the next valid iterator

What this lesson walks through

  1. 01An iterator points INTO the buffer
  2. 02push_back full -> reallocation moves the buffer
  3. 03it now dangles -> UB
  4. 04Fix A: reserve() up front
  5. 05Fix B: use an index, not an iterator
  6. 06erase invalidates from that point on
  7. 07The invalidation rules

it = v.begin() + 1 holds a raw address inside the vector's buffer - it points directly at the element 20.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of Iterator Invalidation and 100+ animated C++ interview lessons.

← Previous
STL: Custom Objects in map/unordered_map — operator< and Hash
Next →
std::string_view & Dangling