skip to content

A C++ class keeps a std::span<const float> into its own std::vector<float> member; why does it break after push_back, and how do you fix it?

level: seniorimportance: should knowfreq 45%

answer

  1. the span cannot see the owner
  2. capacity runs out
  3. old buffer freed
  4. store offset and length instead

basics

~20 s

The span stores the vector's data pointer and a size. A push_back that exceeds capacity reallocates and frees the old buffer, so the span dangles. Store an offset and length and rebuild the span when needed.

solid answer

~40 s

A `std::span` is only a pointer and a size; it has no link to the vector and cannot notice changes. When `push_back` grows the vector past `capacity()`, the vector allocates a new buffer, moves the elements and frees the old one, which invalidates every pointer, iterator and reference into it. The standard spells out that whatever invalidates a pointer into a span's range invalidates the span's elements too, so reading the stored span is a use-after-free that AddressSanitizer reports as `heap-use-after-free`. The robust fix is to store an offset and a length and build the span on demand with `std::span(samples).subspan(off, len)`. Alternatives are reserving a hard maximum and never exceeding it, or storage that never moves. Spans are safest as parameters, where the caller's buffer outlives the call.

code

cpp · 21 lines
cpp
#include <cstdio>
#include <span>
#include <vector>

struct Track {
    std::vector<float> samples;
    std::span<const float> preview;  // non-owning view into samples

    void load(std::size_t n) {
        samples.assign(n, 0.25f);
        preview = std::span(samples).first(n);
    }
    void append(float s) { samples.push_back(s); }  // may reallocate
};

int main() {
    Track t;
    t.load(4);           // capacity 4 with libc++
    t.append(0.75f);     // reallocates: preview now points at freed memory
    std::printf("%g\n", t.preview[0]);  // undefined behaviour
}

go deeper

for a junior

Recall that a span does not own its data, so it becomes invalid when the vector it views reallocates or is destroyed.

for a middle

Walk through push_back past capacity: a new buffer, moved elements, the old buffer freed, and the span still holding the old pointer.

for a senior

Diagnose the bug from an AddressSanitizer report, recognise the temporary-vector variant, and replace stored spans with offsets and lengths or provably stable storage.

for a principal

Set a team rule on where non-owning views may be stored, for example parameters freely and members only with a documented owner invariant, and back it with sanitizer runs.

## A span is a pointer and a size, nothing more A `std::span<const float>` stores where the elements are and how many there are. It holds no reference count, no link to the owning container and no way to learn that the owner changed. The standard states the consequence directly: any operation that invalidates a pointer into the span's range invalidates pointers, iterators and references to elements of the span. The span object is then a **dangling view**, and reading through it is undefined behaviour. ## The member-span bug Consider an audio track object that keeps both the samples and a preview window over them: ```cpp struct Track { std::vector<float> samples; std::span<const float> preview; // view into samples }; ``` The sequence that breaks it: 1. `load` fills `samples` with four values and sets `preview = std::span(samples).first(4)`. The span now holds `samples.data()` and 4. 2. `append` calls `samples.push_back(0.75f)`. The vector is full (with libc++, `assign(4, ...)` leaves capacity 4), so it **reallocates**: it allocates a larger buffer, moves the elements, and frees the old one. 3. `preview` still holds the old pointer. Reading `preview[0]` reads freed memory. Built with `-fsanitize=address`, the program reports `heap-use-after-free` at the read, with the free inside `Track::append`. Nothing in the type system notices. The vector cannot update the span, and the span cannot ask the vector. The same failure follows from every operation that moves or frees the owner's storage: - `push_back`, `insert`, `resize` or `reserve` that grows past capacity; - `shrink_to_fit`, `clear` followed by reuse, or assigning a new vector; - moving the vector into another object, or destroying the owner; - erasing elements, which shifts later ones so the span sees different values or a stale length. ## The temporary-owner bug A second form needs no class at all: ```cpp std::span<const float> s = decode(); // decode() returns std::vector<float> ``` `std::span<const float>` accepts an rvalue vector because its element type is const; the returned vector is destroyed at the end of the full expression, and `s` dangles on the next line. Apple clang warns with `-Wdangling-gsl`: `object backing the pointer will be destroyed at the end of the full-expression`. A non-const `std::span<float> s = decode();` does not compile, because the range constructor accepts an rvalue only when the range is a borrowed range or the element type is const. ## Fixes | situation | fix | |---|---| | span member over a growing vector | store an **offset and length** and build the span on demand: `std::span(samples).subspan(off, len)` | | owner must grow but views must stay valid | `reserve` a hard maximum up front and never exceed it, or use storage that never moves, such as a fixed `std::array` | | span built from a function's returned vector | keep the vector in a named variable first; the span then views a living object | | span crossing an API boundary | document that the span is valid only for the duration of the call, the normal contract for span parameters | The general rule is that span works best as a **parameter**: the caller's buffer is alive for the whole call, so there is nothing to dangle. A span stored as a member or returned from a function needs a written argument for why its owner outlives it. ## How to find these bugs - **AddressSanitizer** reports the read with both stacks: where the memory was freed and where it was read. - **Compiler warnings** such as clang's `-Wdangling-gsl` catch the temporary-owner form. - **Code review**: a `std::span` data member is the signal to ask who owns the storage and what can reallocate it. ## What interviewers listen for A strong answer explains that span is non-owning and cannot observe the owner, walks through reallocation invalidating the stored pointer, mentions the temporary-vector form, and proposes a fix that removes the stored pointer, such as an offset and length, rather than hoping capacity never runs out.

  • Why does std::span<const float> s = make_vector(); compile while std::span<float> s = make_vector(); does not?
    span's range constructor accepts an rvalue range only if the range is a borrowed range or the span's element type is const. A `std::vector` is not borrowed, so `std::span<float>` rejects the temporary, but `std::span<const float>` accepts it and then dangles once the full expression ends. Apple clang flags it with `-Wdangling-gsl`.
  • Does calling samples.reserve(n) in the constructor make the stored span safe?
    Only while the size never exceeds `n`. Within the reserved capacity no insertion reallocates, so the data pointer stays put; but one `push_back` beyond the reserve reallocates and the span dangles again. It also does not help with `erase`, `clear` or moving the vector, so it needs a hard invariant, enforced in code, not a hopeful estimate.

  • Says the span updates automatically when the vector reallocates
  • Believes std::span keeps the vector's buffer alive like a shared_ptr
  • Thinks reserve once fixes a span member forever
  • Says only push_back can invalidate a span into a vector
  • Expects a compiler error whenever a span outlives its owner

Assumes C++20 std::span; the invalidation rule for a span's elements is stated in the C++23 and C++26 drafts.