Undefined behaviour: using an invalidated iterator after push_back / erase on std::vector
An iterator, pointer or reference into a container was used after an operation that invalidated it.
iterator invalidationattempt to dereference a singular iteratorvector iterators incompatibleiterator invalidated 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_backinside 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
- Use
it = v.erase(it)pattern - Reserve capacity up front or use indices
- Iterate over a copy when modifying
- Build with
-D_GLIBCXX_DEBUG
Detailed fix by platform
GCC
g++ -g -D_GLIBCXX_DEBUG -fsanitize=address main.cppaborts with an "attempt to dereference a singular iterator" message
Code examples
erase while iterating
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; // correctHow to diagnose
- Mutation — Container modified in the loop?
- Saved — Iterators/pointers kept?
- Debug — _GLIBCXX_DEBUG result?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
- AddressSanitizer: heap-use-after-free C/C++: ==ERROR: AddressSanitizer: heap-use-after-free on address — memory used after delete/free
- call of overloaded is ambiguous C++: error: call of overloaded 'f(int)' is ambiguous
- cannot declare variable to be of abstract type C++: error: cannot declare variable 'x' to be of abstract type 'Shape' (pure virtual functions)
Most viewed in C/C++
- Bus error C/C++: Bus error (core dumped) — SIGBUS from misaligned access or a bad memory-mapped file
- AddressSanitizer: heap-buffer-overflow C/C++: ==ERROR: AddressSanitizer: heap-buffer-overflow on address — READ/WRITE of size N
- was not declared in this scope C++: error: 'x' was not declared in this scope (undeclared identifier)
Other ways to find it
Where this error sits
Origin: Application & API. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 2 Dec 2026