Skip to content

Commit

Permalink
small fix to the tutorial-ffi destructor example
Browse files Browse the repository at this point in the history
The previous example was erroneously attempting to destroy
uninitialized memory, which was often zeroed (masking the bug).
  • Loading branch information
thestinger committed May 5, 2013
1 parent d74ac9e commit 8f2d71a
Showing 1 changed file with 4 additions and 7 deletions.
11 changes: 4 additions & 7 deletions doc/tutorial-ffi.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,7 @@ wrapping `malloc` and `free`:

~~~~
use core::libc::{c_void, size_t, malloc, free};
#[abi = "rust-intrinsic"]
extern "rust-intrinsic" mod rusti {
fn init<T>() -> T;
}
use core::unstable::intrinsics;
// a wrapper around the handle returned by the foreign code
pub struct Unique<T> {
Expand All @@ -166,7 +162,8 @@ pub impl<'self, T: Owned> Unique<T> {
unsafe {
let ptr = malloc(core::sys::size_of::<T>() as size_t) as *mut T;
assert!(!ptr::is_null(ptr));
*ptr = value;
// `*ptr` is uninitialized, and `*ptr = value` would attempt to destroy it
intrinsics::move_val_init(&mut *ptr, value);
Unique{ptr: ptr}
}
}
Expand All @@ -186,7 +183,7 @@ pub impl<'self, T: Owned> Unique<T> {
impl<T: Owned> Drop for Unique<T> {
fn finalize(&self) {
unsafe {
let mut x = rusti::init(); // dummy value to swap in
let mut x = intrinsics::init(); // dummy value to swap in
x <-> *self.ptr; // moving the object out is needed to call the destructor
free(self.ptr as *c_void)
}
Expand Down

5 comments on commit 8f2d71a

@bors
Copy link
Contributor

@bors bors commented on 8f2d71a May 5, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bors
Copy link
Contributor

@bors bors commented on 8f2d71a May 5, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merging thestinger/rust/ffi = 8f2d71a into auto

@bors
Copy link
Contributor

@bors bors commented on 8f2d71a May 5, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thestinger/rust/ffi = 8f2d71a merged ok, testing candidate = 3b299e8

@bors
Copy link
Contributor

@bors bors commented on 8f2d71a May 5, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bors
Copy link
Contributor

@bors bors commented on 8f2d71a May 5, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fast-forwarding incoming to auto = 3b299e8

Please sign in to comment.