Skip to content

Leak: a Box in an Option payload is never freed (Option[Box[str]] leaks the box and the str) #1535

Closed

Description

@ehartford

Summary

A Box held in an Option payload is never freed when the Option is dropped: neither the box nor what it owns. Route: debug allocator.

Repro (installed nightly v0.15.2.1; origin/main stage1; the #1456 branch)

use std.box.Box

fn main:
    let o: Option[Box[str]] = Some(Box.new("x".clone()))
    print(o.is_some())
$ with run --debug-alloc optbox.w
true
debug-alloc: LEAK addr=… size=16 origin=unknown
debug-alloc: LEAK addr=… size=16 origin=with_alloc
debug-alloc: leak count=2

The same for a recursive enum reached through Option[Box[..]]:

use std.box.Box

enum List:
    Cons(v: i64, next: Option[Box[List]])
    Nil

fn main:
    let l = List.Cons(4, Some(Box.new(List.Cons(5, None))))
    match l:
        .Cons(v, _) => print(v)
        .Nil => print(0)

leak count=1 (the inner box).

Where (reading, not yet under lldb)

A Box local is dropped by mir_emit_box_drop_place (pointee drop + free; #1456 made the pointee drop by type). A Box reached as an enum payload goes through mir_emit_drop_ptr_for_sema_type -> mir_emit_generic_inst_drop_method, which runs Box's Drop only when Sema pre-froze a concrete Drop contract for that Box[T]; otherwise it falls to the struct-field glue, and Box's one field is a raw *mut T — nothing is freed.

Expected

leak count=0 (§2: a value is released by its owner's scope).

Found while fixing #1456.

Activity

  1. ehartford commented on Sep 25, 2026

    @ehartford
    ContributorAuthor

    Data point from the new cross-language suite in benchmarks/ (binary trees, depth 18, with v0.15.2.1):

    Language Peak RSS
    C 17.5 MB
    Rust 17.8 MB
    With 2076.7 MB

    Under --debug-alloc at depth 6 the run reports leak count=4316, which is every node except the 82 tree roots: Box.drop frees the root and drops the Node, but the Option[Box[Node]] fields inside it are never freed. Smallest repro, leak count 1:

    use std.box.Box
    fn main:
        let maybe: Option[Box[i32]] = Some(Box.new(7))
        print(maybe.is_some())
    

    A plain Box[i32] field in a boxed struct is freed correctly (leak count 0), so the gap is specifically the Option payload, as the title says. Peak memory scales with total allocations rather than the live set: 22 MB at depth 12, 99 MB at 14, 456 MB at 16.

  2. ehartford commented on Sep 26, 2026

    @ehartford
    ContributorAuthor

    Verified fixed on main 55739d4: Option[Box[str]] drops the box and the str (--debug-alloc 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