rust-lang / nomicon

The Dark Arts of Advanced and Unsafe Rust Programming
https://doc.rust-lang.org/nomicon/
Apache License 2.0
1.82k stars 262 forks source link

Vec implementation throws UB when dropping RawVec holding ZSTs #424

Open pwbh opened 12 months ago

pwbh commented 12 months ago

In the following page there is something missing to handle ZSTs which leads to a UB

https://github.com/rust-lang/nomicon/blob/ddfa4214487686e91b21aa29afb972c08a8f0d5b/src/vec/vec-zsts.md?plain=1#L1

When Vec is dropped filled with ZSTs, I am getting the following error

error for object 0x1: pointer being freed was not allocated

and indeed we never allocate anything for ZSTs, just pointing to some dangling pointer that represent our ZST.

I suggest a tweak to our Drop trait in raw_vec to handle this case where we deallocate only for T when size of T > 0:

impl<T> Drop for RawVec<T> {
    fn drop(&mut self) {
        if self.cap != 0 && std::mem::size_of::<T>() > 0 {
            let layout = std::alloc::Layout::array::<T>(self.cap).unwrap();
            unsafe {
                std::alloc::dealloc(self.ptr.as_ptr() as *mut _, layout);
            }
        }
    }
}

Please see PR for fix https://github.com/rust-lang/nomicon/pull/425