Dangling references
A dangling reference (or dangling pointer) names storage whose lifetime has ended. Reading or writing through it is undefined behaviour. Locals that went out of scope, deleted heap, and invalidated vector iterators are the usual sources.
Detailed Explanation
A reference is another name for an object. When the object dies, the name does not become "empty". It still spells an address. The compiler may reuse that stack slot for someone else. The heap block may be given to the next new. The next read is a use-after-free.
Classic factories of dangles:
- Return a reference or pointer to a local.
const string& f() { string s = "x"; return s; } - Bind a reference to a temporary and store it.
const string& r = string("x");is OK for the rest of the scope (the temporary is extended).string_view v = string("x");is not:string_viewis not a reference in the language-lifetime sense; the temporarystringdies at the semicolon. vectorreallocation.int& x = v[0]; v.push_back(1);—xmay point at freed memory.deletethen use.delete p; *p = 1;- Lambda capture
[&]that outlives the locals. string::c_str()across a mutation.
The compiler does not track most of these. -Wreturn-local-addr catches the first. AddressSanitizer (-fsanitize=address) catches many heap and stack uses-after-free at runtime. It is the tool you run on tests.
Fixes follow the lifetime:
- Return by value. Move and elision make it cheap.
- Own the object in a
shared_ptrif several handles must keep it alive. - Store an index into a
vectorinstead of a pointer, if the vector can reallocate. - Keep the owner in a variable that outlives every view (
stringlives as long as thestring_view). - Do not detach a thread that captured locals by reference.
A dangling iterator is the same bug with a different type. The invalidation tables on vector, deque, and unordered_map are the contract.
optional<T&> is not standard. A raw T* that might be null is the optional non-owning handle. A reference is never null and never "disengaged"; it is therefore the wrong type for "maybe a dead object".
Undefined behaviour means the program is meaningless, not "I will see garbage". It can delete a later null check. Treat every dangle as a must-fix.
Code Examples
#include <string>
const std::string& bad() {
std::string s = "ada";
return s; // dangles
}
std::string good() {
std::string s = "ada";
return s; // safe
}
int main() {
auto n = good();
(void)n;
}#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string owner = "ada lovelace";
std::string_view view = owner; // ok: owner lives
std::cout << view << '\n'; // prints: ada lovelace
// std::string_view v = std::string("tmp"); // dangles
}Common Gotchas
Temporary bound to `string_view`
implicit conversion from `string` to `string_view` does not extend the `string`'s life when the `string` is a temporary.
Range-for over a temporary's member that returns a reference
`for (char c : load().name)` if `load()` returns a `User` by value and `name` is a `string` member is actually OK (the temporary `User` lives for the loop). `for (char c : load().name.c_str())` is a different, awful idea. Prefer naming the `User`.
ASan is not a proof of absence
it finds many dangles, not all (especially unused stale pointers that are never dereferenced).
`delete` does not change the pointer variable
it still holds the old address. `p = nullptr` after `delete` if `p` lives on.