Skip to content

HashMap.remove leaks the stored key when the key owns memory #1189

Closed

Description

@ehartford

HashMap.remove leaks the stored key when the key type owns memory.

use std.collections.HashMap
fn main:
    var m: HashMap[str, str] = HashMap.new()
    m.insert("beta".to_owned(), "two".to_owned())
    let gone = m.remove("beta").unwrap()
    assert(gone == "two")

WITH_DEBUG_ALLOC=1 ./bin → debug-alloc: LEAK addr=… size=16 origin=unknown, leak count=1. Same with m.remove("beta").unwrap() == "two" inline. Verified on the compiler installed from a91d0bf7 and on a stage1 built from the D44 implementation branch; it does not involve iteration (every traversal probe leaks 0).

Exact lines. rt/rt_core.w with_hashmap_remove: on a hit it rt_memcpys the value into val_out (transport — correct, the value's ownership moves to the caller), sets hm_occ[h] = 0 and decrements the length. The slot's key is never dropped. The table is type-erased (ksz bytes), so the runtime cannot drop it; MAP_REMOVE in src/CodegenDispatch.w (~8335) calls the runtime and builds the Option[V], and emits no key drop either. MAP_CLEAR and scope destruction do it right: they walk live slots with the receiver's sema type (mir_emit_hash_collection_element_drops) before touching the table.

Fix shape. Codegen needs the stored key before the slot is cleared: either a runtime lookup that returns the slot index (then with_hashmap_key_ptr_at + the typed drop, then remove), or a remove variant that transports the stored key out alongside the value so codegen drops it with its sema type. Spec §2.3 (D44): transport is fine, but the map's key has exactly one owner and that owner must release it.

Mission: "Rust calls leaking safe; With calls it a defect."

Found while writing the D44 traversal test (#1187); remove was taken out of that test so it can assert zero leaks, and should go back in with this fix.

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