Fix a Dangling std::string_view — Lifetime Rules for Views and References to Temporaries
A view does not keep what it points at alive. This guide takes a std::string_view from a temporary std::string, watches it print corrupted text with the right length, reads the AddressSanitizer heap-use-after-free report that names the fault line and the free line, and fixes the program by giving the characters an owner that outlives the view.
Written November 21, 2026 · Tested with GCC 13.3.0 · 12 min read
- The first failure: a view of a temporary
- The production shape: the view reads a different string
- The sanitizer report: heap-use-after-free
- The rule both programs broke
Written November 21, 2026
Tested with GCC 13.3.0
What this guide is
std::string_view is a non-owning view: it holds a pointer to a sequence of characters and a length, and it owns neither. The documentation for the class states the consequence directly: it is the programmer's responsibility to ensure that a std::string_view does not outlive the pointed-to character array, and its own example of the bad case is a view taken from a temporary string, which is destroyed at the end of the statement. When the viewed object dies first, the view keeps the address and the length and loses the characters. Reading through it after that point is undefined behavior, which in practice means the program prints corrupted text, prints a different string's text, or crashes, and none of those outcomes is guaranteed to repeat.
The same rule governs references. A temporary object is destroyed as the last step in evaluating the full expression that contains the point where it was created, and binding a reference to a temporary extends the temporary's lifetime only in the direct case: a named local reference bound straight to the temporary. The extension does not survive a function return, never applies to a view at all, and cannot be passed on to a second reference. Every dangling-view bug and every dangling-reference bug is one of those non-extending routes taken by code that assumed the extension, or never knew a temporary was involved.
This guide works through the failure in the order it is met in real code. The first program takes a view of a temporary and prints it one statement later: no crash, the correct length, and corrupted text. The second program adds one allocation after the temporary dies and the view prints that allocation's text instead, which is the form this bug takes in production code, where the wrong output looks plausible. AddressSanitizer then names the defect exactly. A returned reference shows the other face of the same rule, and the fixed program at the end owns the string at the layer that uses the view, which is the only repair that holds in every form.
Build every program in this guide with g++ -std=c++17 -g. The examples use std::string, std::string_view, and lifetime extension, all in their C++17 form; nothing here needs a newer standard. The viewed text is 40 characters long on purpose: a short string would be stored inside the std::string object itself, while a 40-character string allocates its characters on the heap, and the heap allocation is what AddressSanitizer can watch being freed.
The first failure: a view of a temporary
The smallest program that earns the bug is six lines of work:
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string_view label;
label = std::string("temporary-label-that-outlives-its-string");
std::cout << "label size = " << label.size() << '\n';
std::cout << "label = " << label << '\n';
return 0;
}
Line 7 does two things in one statement. It constructs a temporary std::string holding the 40 characters, and it assigns a view of that string to label: the view records the address of the characters and the length 40. Then the statement ends, and the temporary is destroyed at that point, because a temporary is destroyed as the last step in evaluating the full expression that created it. The destructor frees the heap buffer that held the characters. Nothing updates label: a view is a pointer and a length, and neither field knows the owner died. Lines 8 and 9 then read through the view, line 8 reading the length field stored inside the view itself, line 9 reading the characters through the stored address.
Built without a sanitizer, the program exits 0 and prints label size = 40 correctly on every run, because the size lives in the view, not in the freed buffer. The second line is where the undefined behavior shows, and it does not show the same way twice: across repeated runs the first bytes of the printed text were corrupted differently each time, while the tail of the string, ending in that-outlives-its-string, stayed readable. That split is the signature of this bug in a demo. The length is right, part of the text is right, the exit status is right, and the output is still wrong, because the freed memory had only been partly reused by the time the print read it. A test that checks the length, or that greps the output for a substring from the tail, passes against this program.
The production shape: the view reads a different string
Freed memory does not stay empty. The next allocation of the same size usually takes the same block, and then the dangling view reads that allocation's characters, in full, with no corruption at all:
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string_view label;
label = std::string("temporary-label-that-outlives-its-string");
std::string other("reused-buffer-reused-buffer-reused-buffe");
std::cout << "other = " << other << '\n';
std::cout << "label size = " << label.size() << '\n';
std::cout << "label = " << label << '\n';
return 0;
}
$ g++ -std=c++17 -g -o reuse reuse.cpp
$ ./reuse
other = reused-buffer-reused-buffer-reused-buffe
label size = 40
label = reused-buffer-reused-buffer-reused-buffe
The other string is also 40 characters, so its allocation request is the same 41 bytes and the allocator hands the same block back. The view still holds the old address and the length 40, so it prints the 40 characters sitting at that address now, which are other's characters in full. This output repeated identically on every run. Nothing in it looks like a memory bug: the length is right, the text is clean, the program exits 0. It is a wrong-answer bug, and in real code the two strings are a label built in a helper and whatever the program allocated next, so the view surfaces one object's text in another object's place. This is why the demo form, with its visibly corrupted bytes, is the lucky form of the defect.
The sanitizer report: heap-use-after-free
Rebuild the first program with AddressSanitizer and the same read is stopped at the moment it happens:
$ g++ -std=c++17 -g -fsanitize=address -o dangle_asan dangle.cpp
$ ./dangle_asan
=================================================================
==524794==ERROR: AddressSanitizer: heap-use-after-free on address 0x504000000010 at pc 0x775a8387f05f bp 0x7ffdd5d3bb50 sp 0x7ffdd5d3b2f8
READ of size 40 at 0x504000000010 thread T0
#0 0x775a8387f05e in fwrite ../../../../src/libsanitizer/sanitizer_common/sanitizer_common_interceptors.inc:1110
#1 0x775a83556dc3 in std::basic_ostream<char, std::char_traits<char> >& std::__ostream_insert<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*, long) (/lib/x86_64-linux-gnu/libstdc++.so.6+0x156dc3) (BuildId: 753c6c8608b61d4e67be8f0c890e03e0aa046b8b)
#2 0x585879822c82 in std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string_view<char, std::char_traits<char> >) /usr/include/c++/13/string_view:763
#3 0x585879822763 in main /home/droopy/slot1-nov21/dangle.cpp:9
#4 0x775a8302a1c9 (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 8cebda42d140fc2b09639f8b13a5d5f2e617ef09)
#5 0x775a8302a28a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a) (BuildId: 8cebda42d140fc2b09639f8b13a5d5f2e617ef09)
#6 0x585879822464 in _start (/home/droopy/slot1-nov21/dangle_asan+0x2464) (BuildId: c40c0a1e4f7c1db9ff0f5f8f91e723c2919cf672)
0x504000000010 is located 0 bytes inside of 41-byte region [0x504000000010,0x504000000039)
freed by thread T0 here:
#0 0x775a838ff0a8 in operator delete(void*) ../../../../src/libsanitizer/asan/asan_new_delete.cpp:152
#1 0x585879822697 in main /home/droopy/slot1-nov21/dangle.cpp:7
#2 0x775a8302a1c9 (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 8cebda42d140fc2b09639f8b13a5d5f2e617ef09)
#3 0x775a8302a28a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a) (BuildId: 8cebda42d140fc2b09639f8b13a5d5f2e617ef09)
#4 0x585879822464 in _start (/home/droopy/slot1-nov21/dangle_asan+0x2464) (BuildId: c40c0a1e4f7c1db9ff0f5f8f91e723c2919cf672)
previously allocated by thread T0 here:
#0 0x775a838fe548 in operator new(unsigned long) ../../../../src/libsanitizer/asan/asan_new_delete.cpp:95
#1 0x585879822f8f in void std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_construct<char const*>(char const*, char const*, std::forward_iterator_tag) /usr/include/c++/13/bits/basic_string.tcc:229
#2 0x585879822b26 in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string<std::allocator<char> >(char const*, std::allocator<char> const&) /usr/include/c++/13/bits/basic_string.h:649
#3 0x585879822655 in main /home/droopy/slot1-nov21/dangle.cpp:7
#4 0x775a8302a1c9 (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 8cebda42d140fc2b09639f8b13a5d5f2e617ef09)
#5 0x775a8302a28a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a) (BuildId: 8cebda42d140fc2b09639f8b13a5d5f2e617ef09)
#6 0x585879822464 in _start (/home/droopy/slot1-nov21/dangle_asan+0x2464) (BuildId: c40c0a1e4f7c1db9ff0f5f8f91e723c2919cf672)
SUMMARY: AddressSanitizer: heap-use-after-free ../../../../src/libsanitizer/sanitizer_common/sanitizer_common_interceptors.inc:1110 in fwrite
Read the report in the order it is printed. The first line names the error class, heap-use-after-free: the read touched heap memory that had already been freed. The second line gives the access, READ of size 40: 40 is the view's length, which is how you know the reading object is the view and not some other pointer. The fault stack below it ends, at frame #3, at dangle.cpp:9, the print statement, reached through the stream insertion operator for std::string_view at frame #2. That is the use, and it is the least interesting line in the report, because the use is where any dangling view eventually surfaces.
The two stacks after the region line are the diagnosis. The region is 41 bytes, the 40 characters plus the terminating null the string allocated. The freed-by stack names dangle.cpp:7, the assignment statement, reached through operator delete: the temporary's destructor ran at the end of that statement and freed the buffer there. The allocated-by stack also names dangle.cpp:7, through the std::string constructor: the same statement created the string, handed its address to the view, and destroyed it. One line is the whole bug, and the report proves it by putting that line in both stacks. The reuse program fails the same way under the sanitizer, with the fault at its print line: AddressSanitizer quarantines freed blocks instead of recycling them, so the reuse that hides the bug in a plain build cannot happen in a sanitizer build. The addresses, the process id, and the stack-pointer values in this report change on every run; the error class, the read size, the region size, and the three line numbers do not.
The rule both programs broke
The lifetime rules behind the report are three, and each one closes a route that looks safe. First, a temporary object is destroyed as the last step in evaluating the full expression that contains the point where it was created. For the temporary string in line 7, the full expression is the assignment statement, so the string is gone before line 8 runs. Second, a view holds no ownership: constructing or assigning a std::string_view copies an address and a length, and no rule extends the viewed object's lifetime to match the view's. The view can outlive its characters by any amount of code, and every read in that gap is undefined behavior, whether it prints garbage, prints another string, or prints the right text because the freed block happened to survive untouched. Third, lifetime extension for references is narrow. Binding a reference directly to a temporary extends that temporary to the reference's lifetime, but the documented exceptions take the extension away on exactly the routes production code uses: a temporary bound to a return value is not extended, a temporary bound to a reference member in a constructor initializer lasts only until the constructor exits, a temporary bound in a new-expression lasts only until the end of the full expression, and a temporary's lifetime cannot be further extended by passing it on to a second reference. A function that returns a view or a reference into a local or a temporary is therefore returning a dangling handle by construction, whatever its signature promises.
The reference form: a warning, then a segfault
Return the temporary by reference instead of by view and the failure changes shape, because the compiler can see this one:
#include <iostream>
#include <string>
const std::string& make_label() {
return std::string("temporary-label-that-outlives-its-string");
}
int main() {
const std::string& label = make_label();
std::cout << "label size = " << label.size() << '\n';
std::cout << "label = " << label << '\n';
return 0;
}
$ g++ -std=c++17 -g -Wall -Wextra -o refreturn refreturn.cpp
refreturn.cpp: In function 'const std::string& make_label()':
refreturn.cpp:5:17: warning: returning reference to temporary [-Wreturn-local-addr]
5 | return std::string("temporary-label-that-outlives-its-string");
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The warning is exact: the temporary bound to the return value is not extended, so the function returns a reference to an object that is destroyed at the end of the return expression. Note the contrast with the first program, which compiled with no warning at all under the same flags: GCC 13.3.0 catches the returned reference and stays silent on the view assigned from a temporary, which is why the view form reaches production and the reference form usually dies at the build. Ignoring the warning is still possible, and the resulting program does not print corrupted text; it segfaults on the label.size() call at line 10, on every run, because the reference reaches a destroyed string object whose own fields no longer hold the values the call reads. Under AddressSanitizer the same program reports a SEGV on unknown address 0x000000000008 in std::string::size() at refreturn.cpp:10, a deadly-signal report rather than a heap-use-after-free report: the fault is in the string object's bookkeeping, before any character is read. Two forms of one rule, two different failures, and only one of them arrives with a warning.
The fixed program: own the string where the view is used
The repair is not a cast, a copy of the view, or a longer-lived view. It is moving the ownership to the layer that outlives every use of the view. Where a helper builds the text, the helper returns the std::string by value and the caller owns it; the view is then taken from that owned string, in the scope that uses it:
#include <iostream>
#include <string>
#include <string_view>
std::string make_label() {
return std::string("temporary-label-that-outlives-its-string");
}
int main() {
const std::string owner = make_label();
std::string_view label = owner;
std::cout << "label size = " << label.size() << '\n';
std::cout << "label = " << label << '\n';
const std::string& bound = std::string("bound-temporary-lives-as-long-as-the-reference");
std::cout << "bound size = " << bound.size() << '\n';
std::cout << "bound = " << bound << '\n';
return 0;
}
$ g++ -std=c++17 -g -fsanitize=address -o fixed_asan fixed.cpp
$ ./fixed_asan
label size = 40
label = temporary-label-that-outlives-its-string
bound size = 46
bound = bound-temporary-lives-as-long-as-the-reference
The sanitizer build prints both lines and exits clean, with no report, and the plain build prints the same output. Two different mechanisms make the two halves safe, and telling them apart is the point of the program. label is safe because owner is a named object in the same scope: it is constructed before the view, it is destroyed after the prints, and the view never leaves the scope its owner lives in. Returning the string by value is what puts that owner in the caller; the move or copy elision that carries it costs one string object, not a copy of the characters per use, and every later view, substring, and comparison in the scope can share it. bound is safe by the one extension rule that does apply: a named reference bound directly to a temporary extends that temporary's lifetime to the reference's own lifetime, so the temporary string behind bound lives until the end of main. The same binding one level further away, through the return statement in the previous section, extends nothing. Direct binding extends; every indirect route does not, and code review for this defect is checking which of the two a given binding is.
The same ownership move fixes the other shapes this defect takes. A struct that stores a std::string_view member, a label, a name, a key, is storing an address whose owner lives somewhere else; if the struct can outlive the call that built it, the member should be a std::string and views should be taken from the member at each use. A function that accepts a std::string_view parameter is safe in the ordinary case, because the argument's owner lives in the caller across the call; it becomes unsafe only when the function stores the view, returns it, or hands it to work that runs after the call, and then the parameter type is the thing to change, to an owning string or to a caller-owned object the function borrows for a stated lifetime. A cache or registry keyed or labeled by views of caller strings carries the same obligation in reverse: the registry must copy the text it keeps, because the callers' strings are not its to keep alive.
The fixes, ranked
Return the owner, view at the use site. A helper that builds text returns std::string by value; each caller that needs a view takes it from its own owned string, in its own scope. This is ranked first because it makes the lifetime relationship visible in the types: the view's scope sits inside the owner's scope by construction, and no caller can dangle without first deleting the owner it is using.
Store strings in objects that outlive a call; take views from the members at each use. A stored std::string_view member is a stored address with an unstated precondition about somebody else's object. Where the object is kept, cached, queued, or registered, the member holds the text itself, and the cheap non-owning reads happen on demand, against a member whose lifetime is the object's own.
Use direct reference binding only where it is actually direct. const std::string& r = <temporary>; in one scope is defined and extends the temporary. The same text returned from a function, stored in a member, or bound through another reference dangles. Treat any reference or view that crosses a function boundary as borrowing the caller's object, never as carrying a temporary with it.
Keep view parameters for borrow-only calls. A std::string_view parameter whose function reads it during the call and keeps nothing is the use the type exists for. The audit point is the boundary: a view that is stored, returned, captured for later work, or used as a long-lived key has left the borrow-only case and needs an owner behind it.
Run the sanitizer build in the test suite, not as a one-off. The plain build of the first program exits 0 with the right length and a partly right string, and the reuse form is wrong with perfectly clean output. AddressSanitizer is the check that separates those programs from the fixed one, and it only earns that place if the dangling paths are exercised while it is watching.
Which fix for which cause
| What the code or the report shows | Cause | Fix |
|---|---|---|
ASan heap-use-after-free, with the freed-by and allocated-by stacks naming the same statement |
A view taken from a temporary string destroyed at the end of that statement | Own the string in the using scope; take the view from the owner |
| Clean, plausible output that is another string's text, with the right length | The freed buffer was reused by a later allocation of the same size | Same ownership fix; the output being readable is not evidence of safety |
warning: returning reference to temporary at a return statement |
A temporary bound to a return value, which is never lifetime-extended | Return the string by value; let the caller own it and view it |
| A segfault on the first use of a returned reference | The reference designates a destroyed string object | Return by value; heed the warning instead of building past it |
| A stored view member whose text is wrong or corrupted long after construction | The member outlived the string it was taken from | Store a std::string member; take views from it at each use |
| A named local reference bound straight to a temporary, used in the same scope | No defect: direct binding extends the temporary to the reference's lifetime | Keep it, and keep it direct; do not return it or store it onward |
Checklist
- Search for views and references whose initializer names a construction, a conversion, or a function call rather than a named object: each one is a candidate temporary, and each candidate needs its owner's lifetime named.
- For every stored, returned, or captured view, name the object that owns the characters and the scope in which that object dies; if the view can be read after that scope, the code dangles.
- Check return types: a function returning
std::string_viewor a reference must be returning a view of an object the caller owns or that has static lifetime, never of a local or a temporary built inside the function. - Treat a correct length and a clean exit as no evidence: the length lives in the view, and freed memory often survives long enough to print. The sanitizer build is the check.
- Where a temporary is bound on purpose, keep the binding direct and local, and do not let the reference or a view of it leave the scope.
- Keep strings long enough to allocate in the reproducer: a short string stored inside the string object exercises a different path and can hide the heap report this guide's diagnosis rests on.
Related guides on this site
- C++ Pointers and References: Addresses, Dereferencing, and nullptr — the basics of what a reference binds to and what a pointer holds; this guide is the lifetime half of that subject, where the binding is legal, the syntax is right, and the referred object is simply gone.
- Reading an AddressSanitizer Heap-Use-After-Free — Fault, Freed-By, Allocated-By — the three-stack report read in full for a pointer kept past
delete; the report in this guide has the same three stacks, with the free delivered by a temporary's destructor at the end of a statement instead of by an explicit delete. - Fix C++ shared_ptr Cycle Leak — Two Objects Keep Each Other Alive, weak_ptr Breaks the Cycle — the opposite ownership failure: objects that live too long because each keeps the other alive, where this guide's object dies too early because nothing owns it for the view; both are fixed by deciding, per link, which side owns and which side only observes.
Sources
- cppreference, std::basic_string_view — for the class as a non-owning reference to a constant contiguous character sequence, for the programmer's responsibility to ensure a view does not outlive the pointed-to character array, and for the documented bad case of a view taken from a temporary string destroyed at the end of the statement.
- cppreference, Lifetime — for temporary objects being destroyed as the last step in evaluating the full expression that contains the point where they were created, for the lifetime of a reference ending as if it were a scalar object while the referred object's lifetime may end first, and for access outside an object's lifetime being undefined behavior.
- cppreference, Reference initialization — for lifetime extension when a reference is bound to a temporary, and for its exceptions: a temporary bound to a return value is not extended, a temporary bound to a reference member through a new-expression is not extended past the full expression, and a temporary's lifetime cannot be further extended by passing it on to a second reference.
Keep Exploring
Seven tips and seven puzzles so far, each one a short runnable example with the fix explained.
Paste an AddressSanitizer, UBSan, or ThreadSanitizer report and get the bug, the file and line, and the fix \u2014 in plain language.
C++20 and C++23 features, migration paths, and measured trade-offs.
The full C++ hub \u2014 language basics, the standard library, coroutines, and measured comparisons.
Paste a [Service] section and get a plain-language verdict on every sandboxing setting it finds.