From 6edd32bd97b9194c85196b1951bd6a9f15eb310e Mon Sep 17 00:00:00 2001 From: pwbh <127856937+pwbh@users.noreply.github.com> Date: Sat, 7 Oct 2023 14:07:08 +0300 Subject: [PATCH] Added text related to handling dropping in raw vec for ZSTs --- src/vec/vec-zsts.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/vec/vec-zsts.md b/src/vec/vec-zsts.md index 6715f94..657ba9c 100644 --- a/src/vec/vec-zsts.md +++ b/src/vec/vec-zsts.md @@ -214,3 +214,22 @@ impl DoubleEndedIterator for RawValIter { ``` And that's it. Iteration works! + +And that's it. Iteration works! + +One last thing that we need to take into account, is that now when our vec gets dropped it deallocates the memory that was allocated during the time our vec was alive. With ZSTs we did not allocate any memory, and infact we never do. So right now we have unsoundness in our code where we still try deallocate a `NonNull::dangling()` ptr that we use to simulate the ZST in our vec, This means that we would cause an undefined behaviour if we try to deallocate something that we never allocated (obviously and for the right reasons). Lets fix tha, in our raw_vec we are going to tweak our Drop trait and check that we deallocate only types that are sized. + +```rust,ignore +impl Drop for RawVec { + fn drop(&mut self) { + println!("RawVec Drop called, deallocating memory"); + if self.cap != 0 && std::mem::size_of::() > 0 { + let layout = std::alloc::Layout::array::(self.cap).unwrap(); + unsafe { + std::alloc::dealloc(self.ptr.as_ptr() as *mut _, layout); + } + } + } +} +``` +