Skip to content

A generator's owned named local is dropped twice at exhaustion: the next body's scope exit and the saved state both free it #1548

Closed

Description

@ehartford

Spec: §13.4 (generators), §2.4 (a value drops exactly once). A generator's named local that stays owned across a yield is dropped twice when the generator runs to exhaustion: once by the next body's own scope exit, once by the caller's drop of the generator state that carries a copy of it.

fn words() -> Vec[str]:
    var v: Vec[str] = Vec.new()
    v.push("a".clone())
    v.push("bb".clone())
    v.push("ccc".clone())
    v
gen fn each() -> str:
    let v = words()
    var i = 0
    while i < v.len() as i32:
        yield v[i].clone()
        i += 1
fn main:
    var n = 0
    for s in each():
        n = n + s.len() as i32
    print(n)

run --debug-alloc (stage1 of origin/main ba2d5d1, and with the #1412 fixes): DOUBLE FREE … size=128 origin=Vec first_drop=drop#struct __drop_struct_296 second_drop=drop#struct __drop_struct_953 — the Vec's own drop glue, then the generator state struct's.

MIR of __with_generator_next_…: every yield block saves _1.v = copy _2 (a bit copy of the live Vec into the state); the loop-exit block that returns None runs the body's scope exit, drop(_2) @ drop#12 scope-exit _1, and returns with the state still holding the copy; the caller then drops the exhausted state (__drop_struct_953) and frees the same buffer again.

Exact site: lower_generator_next_body (src/MirLower.w) — gen_save_generator_fields copies, never moves, each named local into the state, and the body's scope-exit drops are kept as they were lowered (drop(_2)), so the ownership of a state field is split between the next body's last call and the state itself. One owner is needed: either the next body's returning paths blank the fields they drop (the state is then dropped as a shell) or the body never drops state locals and the state's drop is the only one.

An early break out of the consuming loop (no exhaustion) is clean: only the state drops. Found while building the #1412 generator matrix; #1534 (for-loop state) is the sibling.

Activity

  1. ehartford commented on Sep 26, 2026

    @ehartford
    ContributorAuthor

    Fixed by #1718 (generator locals blanked at exhaustion) and superseded by D69's push generators (#1731 stack), which have no saved state. Verified on main 3ccb998: repro prints 6, leak count=0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions