Key Takeaway

When the number of elements exceeds its capacity(), std::vector performs a reallocation: it allocates a new, larger block of memory, moves the existing elements into it, and frees the old block. Once that happens, every iterator, pointer, and reference that pointed into the old buffer becomes dangling, and using it afterward is undefined behavior (UB). If you know the number of elements in advance, calling reserve() to pre-allocate capacity is the standard way to avoid reallocation entirely.

If you’ve worked with C++ for a while, you’ve probably hit a case where calling push_back a few times suddenly crashes the program, or a reference you were holding onto turns into some garbage number. This post walks through why std::vector reallocates, what iterator invalidation actually means, and how AddressSanitizer catches it, all with minimal example code.

What Is std::vector Reallocation? What’s the Difference Between size and capacity?

One-line answer: When the number of elements exceeds capacity, the vector allocates a new, larger block of memory, moves the elements into it, and frees the old block.

push_back(5) on a full capacity-4 block → in this run elements move to a new capacity-8 block and the old one is freed; it still points to the old block and dangles (UB)

  1. The core difference between size() and capacity() is this: size() is the number of elements the container currently holds, while capacity() is the total number of buffer slots already set aside, enough to hold more elements without any new allocation.
  2. When inserting an element pushes size() past capacity(), a reallocation happens: the vector allocates a new, larger contiguous block, moves the existing elements into it, and deallocates the old buffer. The growth factor here is implementation-defined, not something the C++ standard mandates. The code below prints exactly how this plays out on every push_back.
// Print how size and capacity change on each push_back (growth factor is implementation-defined)
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v;
    const int* old = v.data();
    for (int i = 1; i <= 9; ++i) {
        v.push_back(i);
        bool moved = (v.data() != old);   // buffer address changed = reallocation
        std::cout << "size=" << v.size() << " capacity=" << v.capacity()
                  << (moved ? "  <- reallocated" : "") << '\n';
        old = v.data();
    }
}

Output (g++ 14.2.0, libstdc++, x86_64, -std=c++17):

size=1 capacity=1  <- reallocated
size=2 capacity=2  <- reallocated
size=3 capacity=4  <- reallocated
size=4 capacity=4
size=5 capacity=8  <- reallocated
size=6 capacity=8
size=7 capacity=8
size=8 capacity=8
size=9 capacity=16  <- reallocated

As this output shows, reallocation doesn’t happen on every call — only at the specific points where capacity runs out — and the exact growth pattern here is just a result of this particular libstdc++ build, not something the standard guarantees.

  1. How elements get relocated during a reallocation is decided by std::move_if_noexcept. If the element type’s move constructor is declared noexcept, elements are moved; otherwise, if the type is copyable, they are copied to keep the strong exception guarantee. For more on when move versus copy gets picked, see Copy Constructor vs Move Constructor in C++: Which One Is Called, and When?.

What Is Iterator Invalidation? Which Operations Break Pointers and References?

One-line answer: It’s what happens when a container’s memory reallocation, or an element being removed or relocated, leaves existing iterators, pointers, or references pointing at memory that’s no longer valid — accessing them afterward is undefined behavior (UB).

  1. Since std::vector stores all of its elements in a single contiguous block, once a reallocation frees that block, every pointer, reference, and iterator that pointed into it becomes dangling all at once. That’s a sharp contrast with std::unordered_map, which, as covered in std::map vs std::unordered_map: Which One, and When? (Korean), only invalidates iterators on rehash while references to element nodes stay valid.
  2. The cppreference std::vector “Iterator invalidation” rules, summarized:
    • push_back, emplace_back: if size() exceeds the old capacity() and a reallocation occurs, all iterators (including end()) and all references are invalidated. Otherwise only the end() iterator is invalidated.
    • insert, emplace: if a reallocation occurs, all iterators and references are invalidated. Otherwise, the iterators and references at and after the insertion point (including end()) are invalidated.
    • erase: the erased elements and all iterators/references at and after them (including end()) are invalidated.
    • pop_back: the erased last element and the end() iterator are invalidated.
    • reserve, shrink_to_fit: all iterators/references are invalidated only if capacity changed; otherwise none are.
    • clear, operator=, assign: always invalidate all iterators and references.
    • swap: only the end() iterator is invalidated.
    • Read-only operations: no invalidation.
  3. Bug pattern (a): holding an element reference while calling push_back. If capacity is already full and push_back triggers a reallocation, the existing reference r ends up pointing into freed heap memory.
// UB example: push_back while holding an element reference -> after reallocation it points to freed memory
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {1, 2, 3, 4};
    std::cout << "capacity=" << v.capacity() << '\n';
    int& r = v[0];          // reference to the first element
    v.push_back(5);         // exceeds capacity -> reallocation, r is invalid
    std::cout << "r = " << r << '\n';   // UB: reading freed memory
}

Output [UB, not guaranteed]:

capacity=4
r = 1503387104

ASan excerpt (AddressSanitizer heap-use-after-free summary):

=================================================================
==PID==ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000010 at pc 0x561225a504b2 bp 0x7ffc435840a0 sp 0x7ffc43584098
READ of size 4 at 0x502000000010 thread T0

Dangling-memory bugs like this get caught the instant they happen once you turn on AddressSanitizer (Korean).

  1. Bug pattern (b): calling push_back while iterating. If a reallocation happens mid-loop, both the iterator it you’re iterating with and the loop’s exit condition v.end() become invalid. What happens next is UB: it may crash, or it may quietly produce wrong results.
// UB example: push_back while iterating -> iterator invalidation
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {1, 2, 3, 4};
    for (auto it = v.begin(); it != v.end(); ++it) {
        if (*it == 2) v.push_back(20);   // on reallocation, both it and end() are invalid
    }
    std::cout << "size=" << v.size() << '\n';
}

Output [UB, not guaranteed]:

size=6

ASan excerpt (AddressSanitizer heap-use-after-free summary):

=================================================================
==PID==ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000018 at pc 0x55f17a3b843a bp 0x7ffd151506b0 sp 0x7ffd151506a8
READ of size 4 at 0x502000000018 thread T0

When Should You Use reserve()? How Do You Summarize It for Interviews?

One-line answer: Use it when you know the number of elements you’re going to insert ahead of time, to eliminate unnecessary reallocations, improve performance, and prevent iterator invalidation.

  1. Per cppreference reserve, if new_cap > capacity(), a larger block is allocated and existing iterators are invalidated at that point. But once you’ve secured enough capacity, you can keep adding elements within that range without triggering any further reallocation, which keeps your iterators and references safely valid.

    After reserve(8), push_back(5) stays in the same buffer: no reallocation and it stays valid (*it=1)

  2. A common misuse of reserve() is calling it right before every push_back. cppreference explains that this can make capacity grow linearly instead of exponentially, which can actually increase reallocations and hurt performance. It is best called once, when you know the count up front.

  3. Three safe patterns for preventing iterator invalidation:

    1. Pre-allocate enough capacity with reserve() so the buffer stays the same and iterators remain valid.
    2. When you need to add elements while iterating, loop by index (size_t i) instead of using iterators.
    3. When removing elements while iterating, keep iterating with the next valid iterator that erase() returns.

    Here’s a combined example covering all three patterns.

// Fixed versions: reserve, index loop, using erase's return value
#include <iostream>
#include <vector>

int main() {
    // (1) reserve: no reallocation as long as you stay within the reserved space
    std::vector<int> a = {1, 2, 3, 4};
    a.reserve(8);
    const int* before = a.data();
    auto it = a.begin();
    a.push_back(5);
    std::cout << "reserve: same buffer=" << (a.data() == before)
              << " *it=" << *it << '\n';

    // (2) adding while looping: loop by index (instead of iterators)
    std::vector<int> b = {1, 2, 3, 4};
    for (std::size_t i = 0; i < b.size(); ++i) {
        if (b[i] == 2) b.push_back(20);
    }
    std::cout << "index loop: size=" << b.size() << " last=" << b.back() << '\n';

    // (3) erase: continue with the returned iterator
    std::vector<int> c = {1, 2, 3, 4, 5, 6};
    for (auto e = c.begin(); e != c.end(); ) {
        if (*e % 2 == 0) e = c.erase(e);
        else ++e;
    }
    std::cout << "erase loop:";
    for (int x : c) std::cout << ' ' << x;
    std::cout << '\n';
}

Output:

reserve: same buffer=1 *it=1
index loop: size=5 last=20
erase loop: 1 3 5
  1. Iterator invalidation never produces a compiler warning — it’s undefined behavior (UB) that only shows up at runtime as intermittent garbage values or crashes. That’s why it’s worth clearly separating, in your design, when a container’s size can change from how long you keep references to its elements around.

[Interview one-liner] Since std::vector is backed by contiguous memory, a push_back that exceeds capacity triggers a reallocation, invalidating every iterator and reference at once (UB). If you know the number of elements in advance, pre-allocate with reserve() to avoid the reallocation altogether.

Interview answer template: “A vector keeps its elements in contiguous memory, so when push_back makes size exceed capacity, it reallocates to a bigger block and frees the old one. All iterators, pointers and references then become invalid, and using them is UB. If I know the count, I reserve up front; if I add while looping, I use indices; and when erasing, I continue with the iterator erase returns.”

Shall We Check Your Understanding With a Q&A?

Q1. What’s the difference between size() and capacity() on a std::vector?

A1. size() returns the number of elements the container actually holds right now, while capacity() returns the maximum buffer size it can hold (the slots already reserved) without any additional allocation.

Q2. Does calling push_back always invalidate every iterator?

A2. No. All iterators and element references are invalidated only when inserting the element pushes size() past the old capacity() and triggers a reallocation. If no reallocation happens, only the end() iterator is invalidated — iterators and references to existing elements stay valid.

Q3. How do you avoid iterator invalidation when erasing elements that match some condition while looping?

A3. Since erase() invalidates the erased element and every iterator after it, you need to keep iterating with the valid iterator that erase() returns — the one pointing at the position right after the erased element — like it = v.erase(it);. Using the erase-remove idiom or the non-member std::erase function is also a safe option.

Q4. What happens if you call reserve() right before every single push_back?

A4. Capacity can grow linearly instead of exponentially, which can actually increase reallocations and hurt performance (per cppreference on reserve). Call it once when you know the count up front.