Skip to content

std.regex Captures retains freed pattern code for named lookup #1098

Closed

Description

@ehartford

Regex.captures_at constructs Captures { regex_ptr: self.ptr, ... } at lib/std/regex.w:388. The owned result retains the original Regex's raw compiled-code pointer. Captures.by_name later dereferences that code through regex_group_index (line 675), even after the Regex releases it.

Minimal repro:

use std.regex
fn main:
    let re = Regex.compile("(?<word>abc)").unwrap()
    let caps = re.captures("abc").unwrap()
    re.drop()
    assert(caps.name_text("word") == "abc")

LLDB on the native -O1 binary under WITH_DEBUG_ALLOC=1 WITH_ALLOC_NO_REUSE=1 hit pcre2_code_free_8 from Regex.drop, x0=0x1000c4870. Continuing hit pcre2_substring_number_from_name_8 through Captures.by_name with the identical x0=0x1000c4870. The name lookup uses already-freed compiled code. Local proof: out/c4-validation/regex-captures-lldb.log.

The debug allocator keeps no-reuse memory available, so this particular assertion still passes; it does not establish lifetime safety. Automatic Regex destruction is also currently broken (#1036), hiding this bug on ordinary scope exit. Fixing that destructor requires giving captures their own valid name metadata lifetime. The stdlib facade contract is owned captures output (docs/stdlib_sourcing_plan.md, surface rule 5), not an untracked raw borrow. No workaround shipped.

Activity

  1. ehartford commented on Oct 25, 2026

    @ehartford
    ContributorAuthor

    Triage 2026-10-25, with v0.15.3.0 (main a261b65): does not reproduce; 6d54088 ("own compiled patterns, tables, and capture metadata") made Captures own what it reads.

    $ cat main.w
    use std.regex
    fn main:
        let re = Regex.compile("(?<word>abc)").unwrap()
        let caps = re.captures("abc").unwrap()
        re.drop()
        assert(caps.name_text("word") == "abc")
        print("ok")
    $ with run --debug-alloc main.w
    ok
    debug-alloc: leak count=0 allocations=17
    
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