Skip to content

Instantly share code, notes, and snippets.

@evanw
Created December 29, 2013 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evanw/8167833 to your computer and use it in GitHub Desktop.
Save evanw/8167833 to your computer and use it in GitHub Desktop.
Rust language: Use after free? (rustc 0.8)
struct Foo {
x: int
}
impl Drop for Foo {
fn drop(&mut self) {
println!("drop {}", self.x);
}
}
fn main() {
let mut ptr = ~Foo { x: 0 };
// This fails to compile:
//
// error: cannot assign to `ptr` because it is borrowed
//
// let foo = &ptr;
// println!("foo.x is {}", foo.x);
// ptr = ~Foo { x: ptr.x + 1 };
// println!("foo.x is {}", foo.x);
// This compiles and runs with the following output:
//
// access 0
// drop 0
// access 0
// drop 1
//
// It seems that this is accessing the first object after it is destroyed!
let test = |foo: &Foo| {
println!("access {}", foo.x);
ptr = ~Foo { x: ptr.x + 1 };
println!("access {}", foo.x);
};
test(ptr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment