Skip to content

Objects can be dropped an arbitrary number of times in safe code #25549

Closed
@Thiez

Description

@Thiez

The following function can drop any object arbitrary number of times, using only safe code:

fn drop_n_times<T: Drop>(val: T, times: u32) {
    struct Holder<T: ?Sized>(T);
    let container = Holder(val);
    for _ in 0..times {
        &(*(&container as &Holder<Drop>)).0;
    }
}

struct Foo;
impl Drop for Foo {
    fn drop(&mut self) { println!("dropping"); }
}

fn main() {
    drop_n_times(Foo, 3);
}
dropping
dropping
dropping
dropping

Probably bad :)
Found while researching #25515

Metadata

Metadata

Assignees

No one assigned

    Labels

    I-crashIssue: The compiler crashes (SIGSEGV, SIGABRT, etc). Use I-ICE instead when the compiler panics.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions