skip to content

String Views

std::string_view is a pointer and a length into characters someone else owns, so it is cheap to pass and easy to dangle. Interviewers ask when it is safe to return or store one.

on this pageshow

explore

questions

5

In C++, why does a std::string_view dangle when it views a temporary std::string or a string that later reallocates?

level: middleimportance: must knowfreq 65%

answer

  1. the view borrows
  2. temporary dies at the semicolon
  3. append can move the buffer
  4. SSO hides the crash
  5. store offsets, not views

basics

~20 s

A string_view only borrows characters. A temporary std::string dies at the end of its full-expression, and appending to or reassigning a std::string may move its buffer; either way the view keeps a stale pointer, and reading it is undefined behaviour.

solid answer

~50 s

A `std::string_view` stores a pointer into somebody else's buffer and never learns when that buffer goes away. Two everyday sources: `std::string_view v = read_header_value();` binds to a temporary `std::string` that is destroyed at the `;`, and a view into a `std::string` that is later appended to, reserved, cleared or reassigned, which may reallocate and free the old buffer. The standard spells out the second case: any operation that invalidates a pointer into the viewed range invalidates the view's elements. Reading through such a view is undefined behaviour. Clang warns about the first form (`-Wdangling-gsl`) and AddressSanitizer reports the heap case as `heap-use-after-free`, but short strings stored inline by the small-string optimization can produce silent garbage instead. The fix is to keep the owner alive and unchanged while views exist, or to store offsets and re-slice.

code

cpp · 12 lines
cpp
#include <iostream>
#include <string>
#include <string_view>

int main() {
    std::string buffer = "Host: example.com\r\nAccept: */*\r\n";  // first chunk from the socket
    std::string_view host = std::string_view(buffer).substr(6, 11);

    buffer += "User-Agent: a-client-with-a-long-name/1.0\r\n";  // may reallocate

    std::cout << host << '\n';   // undefined behaviour if the append reallocated
}

go deeper

for a junior

Remember that a string_view does not own the text, so the owner must outlive it.

for a middle

Name the two sources, a temporary destroyed at the end of its full-expression and an owner that reallocates, and the members that cannot invalidate.

for a senior

Diagnose it with clang's dangling warnings and AddressSanitizer, and explain why inline small strings can corrupt silently instead of crashing.

for a principal

Choose designs that cannot dangle by construction, such as offsets or owning copies, wherever a buffer outlives its parse step or keeps growing.

## A view borrows, it never owns A `std::string_view` holds a pointer and a length. It does not hold a reference to a `std::string`, does not keep one alive and is not notified when one changes. Every use of the view is therefore a claim that the characters at that address are still the ones it was made from. When the owner dies or moves its characters, the claim is false, and reading through the view is **undefined behaviour**. The standard ties the two together explicitly: for a view `str`, any operation that invalidates a pointer in the range `[str.data(), str.data() + str.size())` invalidates pointers, iterators and references to the elements of `str`. ## Source 1: a view of a temporary ```cpp std::string read_header_value(); // returns by value std::string_view connection = read_header_value(); // dangles at the ';' ``` The function returns a temporary `std::string`; the view is built from it through `std::string`'s conversion operator; the temporary is destroyed at the end of the full-expression; the view is left pointing at freed memory. The same thing happens with `std::string_view v = a + b;` and with a function that returns `std::string_view` built from a local `std::string`. Clang catches the common shapes at compile time. For the declaration above it prints `warning: object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]`, and for `return name;` from a `std::string_view` function with a local `name` it prints `-Wreturn-stack-address`. Those warnings do not see through a constructor that stores a view in a member, so they reduce the problem without removing it. ## Source 2: the owner changes In an HTTP header parser, views often slice a growing request buffer: - `buffer += next_chunk;` may exceed the capacity, so `std::string` allocates a larger buffer, copies and frees the old one; - `buffer.reserve(n)`, `buffer.clear()`, `buffer = other`, `std::getline(in, buffer)` and `in >> buffer` may all do the same; - `operator[]`, `at`, `data`, `front`, `back` and the iterator functions never invalidate. Any `Header { std::string_view name, value; }` built before the append now points into the freed block. ## Why it sometimes does not crash Undefined behaviour has no required symptom, and two effects hide this one: 1. **The freed block still holds the old bytes** until the allocator reuses it, so the parser often prints the right header in tests. 2. **The small-string optimization changes the failure.** If the request was short enough to live inside the `std::string` object, the view points into the object itself, which is still alive. After the append switches the string to heap storage, those bytes are reused for the heap pointer, size and capacity; the view reads that bookkeeping as characters. In a run on this machine with a 19-character first chunk, the view printed NUL bytes and stray letters instead of the host, and AddressSanitizer reported nothing, because no freed memory was touched. With a first chunk longer than the inline capacity, the same program under `-fsanitize=address` stops with `heap-use-after-free`, as shown below. ## Views into containers of strings The same rule reaches one level further. A view of an element of `std::vector<std::string>` depends on two owners: the vector, which may reallocate and move its elements, and the string element, whose characters may be inline. In a run on this machine, a view of a short element `"Host"` dangled as soon as `push_back` reallocated the vector (AddressSanitizer: `heap-use-after-free`), because the inline characters moved with the element. A view of a long element kept printing correctly, because moving a heap-backed string handed the same buffer to the new element. That survival is an implementation accident, not a guarantee: the standard lets moving a string invalidate pointers into it. ## Fixes - **Finish growing, then slice.** Read the whole header block into the buffer before creating any views. - **Keep the owner alive and unchanged** for as long as any view exists, and make that visible in the code: one scope, one request. - **Store offsets when the buffer must keep growing.** A `{std::size_t pos, len}` pair survives reallocation; re-create the view with `std::string_view(buffer).substr(pos, len)` when you need it. - **Copy what must outlive the buffer.** A value kept after the request is done belongs in a `std::string`. - **Use the tools.** Keep clang's dangling warnings on and run the test suite under AddressSanitizer, knowing that inline small strings can still slip past it.

  • Is std::string_view sv = "Host"; safe to keep for the whole program?
    Yes. A string literal is an array with static storage duration, so it lives until the program ends, and a view of it never dangles. The danger is specific to views of objects with shorter lifetimes: temporaries, locals, and `std::string` buffers that can be freed or reallocated.
  • Why might a dangling string_view print correct text in tests and garbage in production?
    Reading freed memory is undefined behaviour with no required symptom. Right after the free, the block usually still holds the old characters, so a test that reads immediately sees the right text. In production, other allocations reuse the block or the string was short and stored inline, so the same read returns whatever is there now.

  • A string_view keeps the std::string it was made from alive.
  • Appending to a std::string never moves the characters a view points at.
  • If AddressSanitizer is quiet, the views in this code are valid.
  • A view of a function's returned std::string lasts until the end of the scope.
  • A view of a string literal can dangle after the function returns.
open as a page

What is C++17's std::string_view, and why do you pass it by value instead of by const reference?

level: juniorimportance: should knowfreq 60%

basics

~20 s

std::string_view is a read-only, non-owning pointer and length over characters someone else owns. It is two words and trivially copyable, so passing by value is as cheap as a reference without the indirection, and literals convert without allocating.

open as a page

In C++, how does std::string_view::substr differ from std::string::substr, and what goes wrong when find returns npos?

level: middleimportance: should knowfreq 50%

basics

~20 s

std::string::substr returns a new std::string, copying and possibly allocating; std::string_view::substr returns a view into the same characters in constant time. Both throw std::out_of_range when pos exceeds size(). Unchecked, find's npos plus one wraps to 0 and silently selects the whole line.

open as a page

Why is passing std::string_view::data() to a C function such as std::atoi or std::fopen a bug in C++?

level: seniorimportance: should knowfreq 50%

basics

~20 s

A string_view ends by its length, so data() need not be null-terminated. A C function scans for '\0' and reads past the view, giving wrong results or undefined behaviour. Pass a terminated std::string copy or use pointer-and-length APIs.

open as a page

What rule would you set for std::string_view in a C++ codebase's function parameters, return types and data members, and why?

level: principalimportance: should knowfreq 40%

basics

~20 s

Take std::string_view for read-only parameters; return and store std::string by default. A parameter view is safe because the argument outlives the call; a returned or stored view is not. Allow documented views of *this, static data and short-lived parse results.

open as a page