Skip to content

A let of an if/match over a sliced view reads freed memory: the D179 copy-out happens at the join, after the arm dropped its temporary #3165

Closed

Description

@ehartford

Repro

use std.string
fn a(why: &str, k: i32) -> str:
    let tail = if k < 0: why.trim() else: why.slice(2, why.len()).trim()
    tail.to_owned()
print("[" ++ a("x, stored", 1) ++ "]")

Expected [stored]; actual [ ] (the right length, freed bytes). WITH_ALLOC_NO_REUSE=1 prints [stored], so it is a use-after-free. Found writing tools/facade_coverage.w (#3116).

Matrix (with run, installed 4d441ef)

shape result
let t = if c: s.trim() else: s.trim() ok
let t = if c: s.slice(0,n).trim() else: s.slice(2,n).trim() both arms freed
let t = if c: s.trim() else: s.slice(2,n) ok (owned arm)
let t = if c: s else: s.slice(2,n).trim() slice arm freed
fn j(s: &str) -> &str: if c: s.trim() else: s.slice(2,n).trim() compiles; returns a view into a freed temporary (by luck prints right)
let t = s.slice(2,n).trim() (no if) ok: copied before the temp drops

Root cause

--dump-mir of a: the else arm is _9 = move <slice>; _11 = trim(&_9); _5 = copy _11; drop(_9) @ scope-exit and the join then does _3 = copy+retain _12.* from _5, a view into the dropped _9.

Two owners, two defects:

Fix

  • lower_contextual_copy_adjustment: when the adjusted expression is an if or match (through grouping and a block's tail), the arms copy out before their frames close, and the join's result local is the owned type; nested joins propagate.
  • resolve_contextual_join and record_transparent_view_origins_from_nodes carry expr_view_into_temporary from any arm/source, so the return case is refused with the existing §21.1 words.
  • Fixtures: a behavior test for every row of the matrix; a compile-error test for the returned join.

Activity

  1. added
    bug
    on Nov 9, 2026
  2. added a commit that references this issue on Nov 9, 2026
  3. ehartford commented on Nov 9, 2026

    @ehartford
    ContributorAuthor

    Fixed in #3180 (main a46efbc): the join's arms copy out before their temporaries drop; a join of a view into a temporary is marked, so the returned case is refused. Fixtures behav_3165 and err_3165.

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

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions