In C++, why does a std::string_view dangle when it views a temporary std::string or a string that later reallocates?
answer
- the view borrows
- temporary dies at the semicolon
- append can move the buffer
- SSO hides the crash
- store offsets, not views
basics
~20 sA 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 sA `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#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
Remember that a string_view does not own the text, so the owner must outlive it.
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.
Diagnose it with clang's dangling warnings and AddressSanitizer, and explain why inline small strings can corrupt silently instead of crashing.
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.