Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vec implementation throws UB when dropping RawVec holding ZSTs #424

Open
pwbh opened this issue Oct 7, 2023 · 0 comments
Open

Vec implementation throws UB when dropping RawVec holding ZSTs #424

pwbh opened this issue Oct 7, 2023 · 0 comments

Comments

@pwbh
Copy link

pwbh commented Oct 7, 2023

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

@pwbh pwbh mentioned this issue Oct 7, 2023
@pwbh pwbh changed the title Vec implementation throws UB when dropping vec with ZSTs Vec implementation throws UB when dropping RawVec holding ZSTs Oct 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant