Skip to content

Vec implementation throws UB when dropping RawVec holding ZSTs #424

@pwbh

Description

@pwbh

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

# Handling Zero-Sized Types

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 #425

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions