Skip to content

Commit 649e858

Browse files
committed
Fix UB caused by uninitialized reference
fix #104
1 parent 457a72a commit 649e858

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/lib.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -109,11 +109,15 @@ impl<K, V> Node<K, V> {
109109
}
110110
}
111111

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

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

0 commit comments

Comments
 (0)