From 649e858829bce9d47f232412c1df185dc663f794 Mon Sep 17 00:00:00 2001 From: Kogia-sima Date: Sat, 9 Jan 2021 04:27:25 +0900 Subject: [PATCH] Fix UB caused by uninitialized reference fix #104 --- src/lib.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 5abdea2..23cc340 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -109,11 +109,15 @@ impl Node { } } +// drop empty node without dropping its key and value unsafe fn drop_empty_node(the_box: *mut Node) { - // 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::>(); + std::alloc::dealloc(the_box as *mut u8, layout); } impl LinkedHashMap {