From 4804a068258eb1a008cdea949931655e5fdcd3ef Mon Sep 17 00:00:00 2001 From: Maurice Laveaux Date: Mon, 25 Sep 2023 15:26:31 +0200 Subject: [PATCH] Clean up the buffer after every resize. --- bf-vec/src/lib.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/bf-vec/src/lib.rs b/bf-vec/src/lib.rs index b65f9f2..5e76312 100644 --- a/bf-vec/src/lib.rs +++ b/bf-vec/src/lib.rs @@ -87,6 +87,10 @@ impl BfVec { new_buffer, write.len.load(Ordering::Relaxed), ); + + + // Clean up the old buffer. + alloc::dealloc(write.buffer as *mut u8, layout); write.capacity = capacity; write.buffer = new_buffer; @@ -97,20 +101,19 @@ impl BfVec { impl Drop for BfVecShared { fn drop(&mut self) { - // If drop panics make sure that we are in a valid state, leaks memory. - let length = self.len.load(Ordering::Relaxed); - self.len.store(0, Ordering::Relaxed); - unsafe { // Only drop items within the 0..len range since the other values are not initialised. - for i in 0..length { + for i in 0..self.len.load(Ordering::Relaxed) { let ptr = self.buffer.add(i); ptr::drop_in_place(ptr); } - // Drop the storage itself. - ptr::drop_in_place(self.buffer); + let layout = + Layout::from_size_align(self.capacity, mem::align_of::()).expect("Bad layout"); + + // Deallocate the storage itself. + alloc::dealloc(self.buffer as *mut u8, layout); } } }