Skip to content

Commit

Permalink
Fix UB caused by uninitialized reference
Browse files Browse the repository at this point in the history
fix #104
  • Loading branch information
Kogia-sima committed Jan 8, 2021
1 parent 457a72a commit 649e858
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,15 @@ impl<K, V> Node<K, V> {
}
}

// drop empty node without dropping its key and value
unsafe fn drop_empty_node<K, V>(the_box: *mut Node<K, V>) {
// Prevent compiler from trying to drop the un-initialized key and values in the node.
let Node { key, value, .. } = *Box::from_raw(the_box);
mem::forget(key);
mem::forget(value);
// Safety:
// In this crate all `Node` is allocated via `Box` or `alloc`, and `Box` uses the
// Global allocator for its allocation,
// (https://doc.rust-lang.org/std/boxed/index.html#memory-layout) so we can safely
// deallocate the pointer to `Node` by calling `dealloc` method
let layout = std::alloc::Layout::new::<Node<K, V>>();
std::alloc::dealloc(the_box as *mut u8, layout);
}

impl<K: Hash + Eq, V> LinkedHashMap<K, V> {
Expand Down

0 comments on commit 649e858

Please sign in to comment.