# Undefined behaviour: using an invalidated iterator after push_back / erase on std::vector

**Code:** `iterator invalidation` · **Category:** C/C++ · **Seen on:** C/C++

An iterator, pointer or reference into a container was used after an operation that invalidated it.

## Meaning

`push_back` can reallocate a vector, invalidating every iterator and pointer. `erase` invalidates iterators at and after the erased position. The result is crashes or silent garbage, often only in release builds.

## Common causes

- `push_back` inside a range-for over the same vector
- Keeping a pointer to an element across insertions
- Erasing in a loop with a stale iterator
- Using `end()` saved before modification

## Quick fix

1. Use `it = v.erase(it)` pattern
2. Reserve capacity up front or use indices
3. Iterate over a copy when modifying
4. Build with `-D_GLIBCXX_DEBUG`

## Detailed fix by platform

### GCC

1. `g++ -g -D_GLIBCXX_DEBUG -fsanitize=address main.cpp` aborts with an "attempt to dereference a singular iterator" message

## Code examples

### erase while iterating

```cpp
for (auto it = v.begin(); it != v.end(); ++it)
    if (*it == 0) v.erase(it);          // invalidates it
for (auto it = v.begin(); it != v.end();)
    it = (*it == 0) ? v.erase(it) : it + 1;   // correct
```

## How to diagnose

1. **Mutation** — Container modified in the loop?
2. **Saved** — Iterators/pointers kept?
3. **Debug** — _GLIBCXX_DEBUG result?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/iterator-invalidation-vector)
