skip to content

In C++, what happens when a function returns a reference or a pointer to one of its own local variables?

level: juniorimportance: must knowfreq 72%

answer

  1. where the local actually lives
  2. lifetime ends at the closing brace
  3. an address survives, the object does not
  4. views over local buffers count too
  5. return by value instead

basics

~20 s

The local is destroyed when the function returns, so the caller receives a dangling reference or pointer. Any read or write through it is undefined behaviour: it may show the old value, garbage, or crash. Return by value instead.

solid answer

~50 s

A local variable has **automatic storage duration**: its lifetime ends when the function returns, and the stack memory it used is reused by the next call. A returned `T&` or `T*` still holds that address, so any later read or write through it is undefined behaviour — it may appear to work, print garbage or crash, and the outcome changes with the optimisation level. The same trap applies to returning a `std::string_view` or `std::span` over a local `std::string` or `std::vector`: the view outlives the buffer. Clang (`-Wreturn-stack-address`) and GCC (`-Wreturn-local-addr`) warn by default about the direct case, but not when the address first passes through another function. The repair is to return by value — copy elision and implicit move make that cheap — or to return a reference only to an object that outlives the call, such as a member of `*this` or an object the caller passed by reference.

code

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

const std::string& greeting(const std::string& name) {
    std::string text = "Hello, " + name;
    return text;               // dangling: text dies at the closing brace
}

int* counter() {
    int n = 42;
    return &n;                 // dangling: n lives in this stack frame
}

std::string_view label(int id) {
    std::string s = "item-" + std::to_string(id);
    return s;                  // dangling view of a destroyed std::string
}

int main() {
    std::cout << greeting("Ada").size() << '\n';
    std::cout << *counter() << '\n';
    std::cout << label(7) << '\n';
}

go deeper

for a junior

Recall that locals die when the function returns, and that a returned reference or pointer to one dangles. Say undefined behaviour, then fix it by returning by value.

for a middle

Explain automatic storage duration, why the stale value often still prints, and that views such as string_view and span dangle exactly like references.

for a senior

Show where compiler warnings stop: an address laundered through a helper compiles silently. Mention lifetimebound annotations and treating the warning as an error in CI.

for a principal

Argue for API rules that make this hard: functions that build data return owning types, views appear only in parameters, and dangling warnings are errors in every build.

## Why the object is gone Every variable declared inside a function body without `static` or `thread_local` has **automatic storage duration**. Its lifetime begins at its declaration and ends when control leaves the enclosing block; for class types the destructor runs at that point. When the function returns, all of its locals are destroyed and the stack frame that held them is free for the next call. A reference or pointer is only an address. Returning `const std::string&` or `int*` copies that address to the caller, but nothing keeps the object behind it alive. The caller now holds a **dangling** reference or pointer. In the standard's terms, the pointer's value has become an *invalid pointer value*: indirection through it is undefined behaviour, and even copying or comparing it is implementation-defined. ## What the compiler catches and what it misses Both major compilers diagnose the direct case without any extra flag: | Pattern | Clang | GCC | |---|---|---| | `return local;` from a function returning `T&` | warns (`-Wreturn-stack-address`) | warns (`-Wreturn-local-addr`, on by default) | | `return &local;` from a function returning `T*` | warns | warns | | returning a `std::string_view` built from a local `std::string` | warns in Clang 21 | not documented for views | | the address passes through a helper first, e.g. `return largest(localVector);` | silent | silent | The last row is the dangerous one. The helper returns a reference into its argument, the compiler cannot see that relationship across the call, and the function compiles cleanly. Clang's `[[clang::lifetimebound]]` attribute on the helper's parameter restores the warning by telling the compiler the result refers into that argument. A warning is not an error: the program still builds and runs. Treat these warnings as errors in your build, because the code behind them is never correct. ## What "undefined" looks like in practice Because the memory is still mapped, the first read often returns the old bytes, so the bug survives tests: - at `-O0` the stale value may still be in the dead stack slot and print correctly; - one call later, another function overwrites the slot and the "same" reference shows garbage; - with optimisation the compiler may drop the store entirely, since no valid program could observe it; - a destroyed `std::string` may have freed its heap buffer, so reading through the reference touches freed memory. None of these outputs is the answer. The only correct statement is that the behaviour is undefined, and that whatever the program prints today it may not print tomorrow. ## Views and other non-owning handles dangle the same way The rule is not limited to `T&` and `T*`. Any type that refers to storage it does not own carries the same risk when the storage belongs to a local: - a `std::string_view` built from a local `std::string`, or a `std::span` over a local `std::vector` or array; - an iterator into a local container, returned so the caller can "continue from here"; - the pointer from `c_str()` or `data()` of a local string; - a lambda that captures a local by reference (`[&]`) and is returned or stored. Each of these copies an address out of a frame that is about to disappear. The view types are especially easy to miss because they look like values: they are cheap to copy, they are passed by value, and nothing in the signature `std::string_view name()` says that the characters live elsewhere. When reviewing a function, check every return type that does not own its data and ask what owns the data it points into. ## Repairing it 1. **Return by value.** `std::string greeting(...)` returns the object itself. Since C++17 a returned prvalue is constructed directly in the caller, and returning a named local is elided or, failing that, treated as an rvalue and moved, so the cost is usually nothing or one move. 2. **Return a reference only to something that outlives the call**: a data member of `*this` (and only while that object lives), a `static` object, or an object the caller passed in by reference. 3. **Return an owning type instead of a view.** A function that builds text should return `std::string`, not `std::string_view`; a function that builds a buffer returns `std::vector`, not `std::span`. ## Interview checklist - Name the storage duration: locals are automatic, and their lifetime ends at the closing brace. - Say "undefined behaviour", not "returns garbage": a correct-looking result is one possible outcome. - Mention that both compilers warn on the direct case but miss the indirect one. - Offer the fix: return by value, and explain why it is not expensive. - Extend the idea to views: a `std::string_view` or `std::span` dangles the same way a reference does.

  • Is it safe to return a reference to a data member from a member function?
    Yes, as long as the object outlives every use of the reference. `const std::string& name() const { return name_; }` is fine on a long-lived object, but calling it on a temporary, such as `make_user().name()`, and keeping the reference leaves it dangling at the end of the full-expression. Return by value when callers commonly use temporaries.
  • Why does returning a large local by value not cost a full copy?
    Since C++17, a returned prvalue initialises the caller's object directly, with no temporary. For a named local the compiler usually applies NRVO, building it in the caller's storage; when it cannot, the return statement treats the local as an rvalue and moves it. A `std::string` or `std::vector` therefore costs at most one cheap move.

  • The local stays alive until the caller has finished using the reference.
  • It is safe because the value printed correctly in my test.
  • Returning a reference to a local is a compile error, so it cannot ship.
  • A const reference return extends the local's lifetime like a const reference binding does.
  • Returning a string_view of a local string is fine because string_view copies the characters.