skip to content

In C++, why does reading through a reference to a std::vector element taken before a push_back become undefined behaviour?

level: middleimportance: must knowfreq 68%

answer

  1. where the elements live
  2. size versus capacity
  3. a new buffer, then the old one freed
  4. references, pointers and iterators alike
  5. keep an index, or reserve first

basics

~10 s

A std::vector stores its elements in one heap buffer. When push_back needs more capacity it allocates a new buffer, moves the elements and frees the old one, so earlier references, pointers and iterators dangle.

solid answer

~50 s

A `std::vector` keeps its elements contiguously in a single heap buffer of `capacity()` slots. If `push_back` (or `emplace_back`, `insert`, `resize`) needs more room than the current capacity, the vector allocates a larger buffer, moves or copies the elements across and frees the old one. The standard says that reallocation **invalidates all references, pointers and iterators** to the elements, plus the end iterator. A reference such as `Order& best = book.front();` still points into the freed buffer, so reading it is a use-after-free: undefined behaviour that often prints stale or garbage data rather than crashing. Whether a given call reallocates depends on capacity, which is implementation-specific, so the bug can hide in tests. The fixes: keep an index instead of a reference, call `reserve()` up front when the final size is known, take the reference after the last insertion, or use a container whose elements do not move, such as `std::deque` for end insertions or `std::list`.

code

cpp · 17 lines
cpp
#include <iostream>
#include <string>
#include <vector>

struct Order { int id; std::string symbol; };

int main() {
    std::vector<Order> book;
    book.push_back({1, "ABC"});
    Order& best = book.front();          // reference into the vector's buffer
    auto it = book.begin();              // iterator into the same buffer

    book.push_back({2, "XYZ"});          // size 2 > capacity 1: reallocates

    std::cout << best.symbol << '\n';    // undefined behaviour: best dangles
    std::cout << it->id << '\n';         // undefined behaviour: it is invalidated
}

go deeper

for a junior

Recall that a vector keeps its elements in one buffer and that growing it can move them, so references taken before push_back may dangle.

for a middle

Explain size versus capacity, the allocate-move-free sequence and the standard's rule that reallocation invalidates all references, pointers and iterators.

for a senior

Spot the hidden versions: a range-for that inserts, a cached element pointer in a long-lived object, growth that only reallocates on large production inputs.

for a principal

Decide where element stability is a design requirement and choose indices, reserve contracts or node-based containers so the rule never depends on reviewers noticing.

## The layout that makes it happen `std::vector<T>` owns one contiguous heap allocation. `size()` is the number of live elements and `capacity()` the number of slots in that allocation. While `size() < capacity()`, `push_back` constructs the new element in the next free slot and nothing else moves. When the vector is full, `push_back` must **reallocate**: 1. allocate a new, larger buffer; 2. move (or copy, if the move constructor may throw and a copy is available) every element into it; 3. destroy the old elements and free the old buffer. The standard's wording for the insertion functions is explicit: if the new size exceeds the old capacity, reallocation happens, and "reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence, as well as the past-the-end iterator." ## Why the reference dangles A reference to an element is just the address of a slot in the old buffer. After step 3 that buffer belongs to the allocator again. Reading through the reference is a **use-after-free**: - the bytes may still hold the old value, so the program prints the right answer; - the allocator may have reused the block, so the program prints someone else's data; - for a type such as `std::string`, the old element's destructor ran, so its members may point at memory that was itself freed; - writing through the reference silently corrupts whatever now lives there. All of these are one outcome of **undefined behaviour**; none is guaranteed. ## Why it hides in tests How capacity grows is the library's choice. In libc++ the capacity after successive `push_back` calls on an empty `std::vector<int>` runs 1, 2, 4, 8, 16; other libraries use other factors. A test that inserts three items may never reallocate, while production inserts the thousandth item and does. The same code can be correct for one input and undefined for another. ## Common shapes of the bug | Shape | What dangles | |---|---| | `T& first = v[0]; v.push_back(x); use(first);` | the reference | | `for (auto& e : v) if (cond(e)) v.push_back(e);` | the hidden iterators of the range-for | | `auto it = v.begin(); v.insert(v.begin(), x); *it;` | the iterator, even without reallocation, because elements shifted | | `v.push_back(v[0]);` | not a bug: the standard library must handle an argument that refers into the vector | The last row is worth knowing because candidates often flag it: `push_back` makes no exception for an argument that aliases an element, so the library must cope, and both libc++ and libstdc++ construct the new element in the new buffer before moving the old elements and freeing the old storage. ## Repairs - **Hold an index**, not a reference: `std::size_t best = 0;` stays meaningful across reallocation. - **Reserve** when the final size is known: after `reserve(n)`, no reallocation happens until the size exceeds `n`. - **Re-acquire** the reference or iterator after the last mutation, or use the iterator that `insert` and `erase` return. - **Choose a node-stable container** when references must survive growth: `std::list` never moves elements, and `std::deque` keeps references valid on `push_back` and `push_front` (its iterators are still invalidated). ## What to ask in a code review When a reference, pointer or iterator into a `std::vector` is stored or held across a call, ask three questions: 1. Can anything between taking the handle and using it insert into or resize this vector, including a callback or a function that receives the vector by non-const reference? 2. Is the handle stored somewhere that lives longer than one statement, such as a member, a map value or a lambda capture? 3. Is there a documented capacity guarantee, such as a `reserve` with a proven upper bound, that the code relies on? If the answer to the first two is yes and the third is no, the code has a latent use-after-free. Erasing has its own variant: `erase` invalidates iterators and references at or after the erased position, so a stored handle to a later element dangles even though no buffer was freed. The full per-container invalidation tables belong with the material on iterators; the point here is recognising the dangling access and its consequence.

  • Does calling reserve() make it safe to keep references across push_back?
    Only up to the reserved size. After `reserve(n)`, insertions that keep `size() <= n` do not reallocate, so existing references and iterators before the insertion point stay valid. The moment the size exceeds `n` the vector reallocates and every reference dangles again. It is a guarantee you must re-check whenever the input can grow.
  • Why is `v.push_back(v[0])` not a dangling-reference bug?
    The argument refers into the buffer that reallocation will free, but the standard's requirements on `push_back` make no exception for such an argument, so the library must handle it. libc++ and libstdc++ both construct the new element in the new buffer first, and only then move the old elements and release the old storage.

  • push_back only adds at the end, so references to earlier elements stay valid.
  • A reference is safer than an iterator because only iterators get invalidated.
  • The vector doubles every time, so I can predict exactly when it reallocates.
  • If the program printed the right value, the reference must still be valid.
  • Calling reserve once makes element references permanently stable.