skip to content

A lazy C++20 coroutine takes const std::string& and is resumed after the caller's temporary has died; why does it read freed memory, and how do you fix it?

level: seniorimportance: should knowfreq 45%

answer

  1. parameters are copied into the frame
  2. a reference copies as a reference
  3. temporary dies at the semicolon
  4. captures live in the closure
  5. take it by value

basics

~20 s

The frame copies parameters, but a reference parameter is copied as a reference to the caller's object. A temporary passed to it dies at the end of the call's full-expression, so a later resume reads a destroyed string. Take the parameter by value instead.

solid answer

~50 s

When a coroutine is called, the standard creates a **copy of each parameter** in the frame: a by-value parameter's copy is direct-initialised from an xvalue referring to the parameter (so it is moved where possible), but a **reference parameter's copy is a reference bound to the same object**. With a lazy coroutine nothing runs until the first `resume()`, and a temporary such as `std::string(32, 'x')` is destroyed at the end of the full-expression that made the call — so the coroutine later reads a dead string: undefined behavior, which AddressSanitizer reports as `stack-use-after-scope`. The same applies to `std::string_view`, `std::span` and raw pointers, to `this` in member coroutines, and to captures of a lambda coroutine, which live in the closure object rather than the frame. The fix is to take what the coroutine needs **by value**, or pass lambda data as parameters instead of captures.

code

cpp · 31 lines
cpp
#include <coroutine>
#include <cstdio>
#include <exception>
#include <string>

struct Lazy {
    struct promise_type {
        Lazy get_return_object() { return Lazy{Handle::from_promise(*this)}; }
        std::suspend_always initial_suspend() noexcept { return {}; }  // lazy start
        std::suspend_always final_suspend() noexcept { return {}; }
        void return_void() {}
        void unhandled_exception() { std::terminate(); }
    };
    using Handle = std::coroutine_handle<promise_type>;
    explicit Lazy(Handle h) : h(h) {}
    Lazy(const Lazy&) = delete;
    ~Lazy() { h.destroy(); }
    void run() { h.resume(); }
    Handle h;
};

// The frame copies the reference, not the string it refers to.
Lazy log_tagged(const std::string& tag) {
    std::printf("[%s] started\n", tag.c_str());
    co_return;
}

int main() {
    Lazy job = log_tagged(std::string(32, 'x'));  // the temporary dies at the ;
    job.run();  // undefined behavior: reads the destroyed string
}

go deeper

for a junior

Recall that a coroutine may run later than the call, so anything it refers to must still exist when it resumes.

for a middle

Explain the parameter-copy rule: values are moved into the frame, references are copied as references, and temporaries die at the end of the full-expression.

for a senior

Spot the lambda-capture and this cases, fix them with by-value parameters or owned pointers, and confirm with AddressSanitizer.

for a principal

Turn the rule into team policy — no reference or view parameters on suspending coroutines without a documented owner, no capturing lambda coroutines.

## What the frame keeps When a coroutine is called, the standard creates a copy of every parameter at the start of the frame: - for a parameter of **non-reference** type `T`, the copy is a variable of type `T` direct-initialised from an xvalue referring to the parameter — a by-value `std::string` is **moved** into the frame; - for a parameter of **reference** type, the copy is a reference bound to the **same object** as the parameter. Names in the body refer to these copies. So a by-value parameter belongs to the coroutine, and a reference parameter still belongs to the caller. The standard's own note warns that resuming after the referred-to object's lifetime has ended is likely undefined behavior. ## How the dangling happens Walk through `Lazy job = log_tagged(std::string(32, 'x'));` with a lazy coroutine: 1. The temporary `std::string` is created. 2. `log_tagged` is called; the frame stores `tag` as a reference to the temporary. 3. `initial_suspend()` returns `std::suspend_always`, so the body does not run; the call returns `job`. 4. The full-expression ends and the temporary is **destroyed**. 5. `job.run()` resumes the coroutine, which reads `tag` — a reference to a destroyed object. AddressSanitizer reports `ERROR: AddressSanitizer: stack-use-after-scope` with a `READ` inside `std::string`. Without a sanitizer the program may print garbage, crash or appear to work: it is undefined behavior. An **eager** coroutine (`std::suspend_never` at the start) is only safe until its first real suspension; anything after a `co_await` has the same problem. ## The same bug in other shapes | Shape | What the frame holds | Dangles when | |---|---|---| | `const std::string&` parameter | a reference | the argument was a temporary or is destroyed before resumption | | `std::string_view`, `std::span<T>` parameter | a view (copied by value) | the viewed buffer dies before resumption | | member function coroutine | the object's address, not a copy of the object | the object is destroyed or moved before resumption | | lambda coroutine with captures | a reference to the closure object | the closure, usually a temporary, dies at the end of the full-expression | The lambda row surprises people most. In `[tag]() -> Lazy { ... co_return; }()`, `tag` is a member of the closure object; the coroutine is the lambda's `operator()`, which refers to the closure through its object parameter. Once the immediately invoked closure is destroyed, every capture is gone, even though it was captured "by value". ## Fixes 1. **Take parameters by value** when the coroutine may outlive the call: `Lazy log_tagged(std::string tag)`. The string is moved into the frame and lives as long as the coroutine. 2. **Pass lambda data as parameters, not captures**: `[](std::string tag) -> Lazy { ... }(std::move(tag))` — parameters are copied into the frame, captures are not. 3. **Keep the object alive** for member coroutines: have the coroutine hold a `std::shared_ptr` to its object (for example via `shared_from_this()`) taken as a by-value parameter or local before the first suspension. 4. **Convert views to owners** at the boundary: a coroutine that receives a `std::string_view` copies it into a `std::string` local before its first suspension. ## Why nothing warns The example compiles cleanly with `clang++ -std=c++20 -Wall -Wextra`: binding a temporary to a `const std::string&` parameter is ordinary C++, and whether the coroutine reads it after suspension depends on the promise type's `initial_suspend` and on the caller — information the warning machinery does not connect. Treat the absence of a warning as no evidence at all; the sanitizer run is what finds it. ## Review rules that catch it - A coroutine that may suspend should not take reference, view or pointer parameters unless the API documents who keeps the object alive. - Lambda coroutines should not capture; they take parameters. - Run tests that exercise coroutines under AddressSanitizer, because the bug appears only when the resumption happens after the caller's full-expression.

  • Is a by-value std::string parameter copied or moved into the frame?
    The standard direct-initialises the frame's copy from an xvalue referring to the parameter, so `std::string`'s move constructor is selected: the argument is copied or moved into the parameter as usual, then moved into the frame. The coroutine owns that string for its whole lifetime.
  • Why does capturing by value in a lambda coroutine not help?
    Captured values are members of the closure object, and a lambda coroutine is the closure's `operator()`, which reaches them through a reference to that object. The frame copies the parameters, not the closure, so if the closure was a temporary — as in an immediately invoked lambda — its captures die at the end of the full-expression. Pass the values as parameters instead, which are copied into the frame.

Leaving a note saying the parcel is on your desk instead of taking the parcel with you: when you come back, the desk may have been cleared. A by-value parameter is taking the parcel.

  • The coroutine frame copies the string a reference parameter refers to.
  • Capturing by value in a lambda coroutine keeps the data alive.
  • std::string_view parameters are safe because the view is copied.
  • If the coroutine starts eagerly, reference parameters are always safe.
  • The temporary lives until the coroutine object is destroyed.

Assumes C++23; the parameter-copy rules for coroutines are C++20's and unchanged since.