rust-lang / rust-lang/rust

Local variable deallocated out of order in the panic path?

Open
#147,875 6 comments 0 reactions 1 assignee View on GitHub

@sladyn98 is already working on this.

Since Nov 26, 2025.

A-borrow-checker A-destructors C-bug I-lang-radar T-lang T-opsem
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I'm not sure if this is a bug or not.

#![allow(unused)]

use std::fmt::Display;

struct Wrap<T: Display>(T);
impl<T: Display> Drop for Wrap<T> {
    fn drop(&mut self) {
        println!("{}", self.0);
    }
}

fn main() {
    let x;
    {
        let y = 1;
        x = Wrap(&y);
        panic!();
    }
}

In the above code, I expected that, conceptually, the memory for y is deallocated, then the destructor for x is ran, then the memory for x is deallocated. Therefore, I would expect the code to not compile, since the Drop impl would be accessing freed memory.

Instead, the code compiles and runs fine, panicking and printing 1. Miri does not detect any UB.

Note that, if the value inside y has a destructor, then the code doesn't compile, as expected.

Removing the panic causes the code to stop compiling, as expected. Replacing the panic with drop(x) causes the code to compile again.

I am unable to cause UB with this behavior, but I still find it extremely weird.

Possibly related to https://github.com/rust-lang/rust/issues/128225

Meta

Reproducible on the playground with version 1.92.0-nightly (2025-10-18 6380899f32599ea25615)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.