Skip to content

for-comprehension over Result: the failure arm moves the carrier twice and frees the Err payload the result owns (double free) #1504

Closed

Description

@ehartford

Found by #1414's new validate-ownership rule ("a move of an already-moved place"), sweeping --validate-all over test/, examples/ and lib/std. Stage2 of main f1e3bd2:

fn get_result(x: i32) -> Result[i32, str]:
    if x > 0: Ok(x) else: Err(f"negative {x} with a tail long enough to live on the heap for sure")

fn main:
    let r: Result[i32, str] = for x in get_result(5); y in get_result(-1):
        yield x + y
    match r:
        Ok(_) => assert(false)
        Err(e) => print(e)

run --debug-alloc prints the error and then:

debug-alloc: DOUBLE FREE addr=... size=128 origin=unknown first_drop=drop#enum __drop_enum_425 second_drop=drop#struct __drop_struct_16

The failure arm of the second generator moves the carrier twice (--dump-mir, test_result_second_err in test/behavior/behav_for_comprehension.w):

bb9: {
    StorageLive(_14);
    _14 = move _8;
    StorageLive(_15);
    _15 = move _8;          // the same Result[i32, str] again
    _9 = move _14;          // becomes the comprehension's result
    _14 = const zst(ty430);
    _8 = const zst(ty430);
    _8 = const zst(ty430);
    drop(_15) @ drop#20 scope-exit _15;   // frees the Err payload _9 still owns
    ...
}

The first generator's failure arm (bb10) has the same shape over _3. --validate-all said ok before #1414; with it: move of _8, which a path reaching it already moved out (Moved) and nothing re-initialized: two owners free one value (§2.5.1). behav_for_comprehension.w and spec_ss13_6a_option_and_result_for_comprehensions.w pass only because their Err payloads are string literals.

Expected: the short-circuit arm moves the failed carrier into the result once (the second binding is either a borrow or absent), the program prints once and exits with no double free, and validate-all is ok.

Activity

  1. ehartford commented on Sep 26, 2026

    @ehartford
    ContributorAuthor

    Fixed by #1718 (for-comprehension failure arm binds the carrier once). Verified on main 3ccb998: the repro prints once, no double free, 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