Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drop skipped on panic #27906

Closed
Stebalien opened this issue Aug 19, 2015 · 7 comments
Closed

Drop skipped on panic #27906

Stebalien opened this issue Aug 19, 2015 · 7 comments

Comments

@Stebalien
Copy link
Contributor

I was working on a patch for @bluss's arrayvec and ran into the following issue. In the code below, I'm trying to keep the Test struct from dropping twice even if it panics on drop. If I explicitly drop the Test when reading it out of the array (using ptr::read), everything works. However, if I don't explicitly drop it (see XXX), it drops (good), panics (good), but then guard isn't dropped (bad) so the Test is dropped a second time (bad).

Sorry for the generic title.

use std::{mem, ptr};

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

struct Container(Option<[Test; 1]>);

impl Drop for Container {
    fn drop(&mut self) {
        /// Prevents Container's contents from dropping.
        struct Guard<'a>(&'a mut Container);
        impl<'a> Drop for Guard<'a> {
            fn drop(&mut self) {
                unsafe {
                    ptr::write(&mut (self.0).0, None);
                }
            }
        }
        {
            let guard = Guard(self);
            {
                unsafe {
                    let v = ptr::read(&mut (guard.0).0.as_mut().unwrap()[0]);
                    drop(v); // XXX: If removed, guard is never dropped and Test gets dropped twice.
                }
            }
        }
    }
}
fn main() {
    let c = Container(Some([Test]));
}
@bluss
Copy link
Member

bluss commented Aug 19, 2015

cc @pnkfelix since it's drop related

@alexcrichton
Copy link
Member

I believe this is a dupe of #14875, so closing in favor of that

@Stebalien
Copy link
Contributor Author

@alexcrichton Looks like it. Thanks.

@bluss
Copy link
Member

bluss commented Aug 20, 2015

@Stebalien did you find a bug in arrayvec?

@Stebalien
Copy link
Contributor Author

@bluss bluss/arrayvec#3

@bluss
Copy link
Member

bluss commented Aug 20, 2015

FWIW, that feels like a panic safety bug in arrayvec, not really a bug in rust?

@Stebalien
Copy link
Contributor Author

The bug in rust is that my PR doesn't work unless the item is dropped explicitly by calling drop on it.

Steven Allen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants