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

Fix: Unsafe Undefined Behavior - Zero Sized PlaneData #23

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions src/plane.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,10 @@ impl<T: Pixel> std::ops::DerefMut for PlaneData<T> {
impl<T: Pixel> std::ops::Drop for PlaneData<T> {
fn drop(&mut self) {
// SAFETY: we cannot dealloc too much because we know the length of the data
unsafe {
dealloc(self.ptr.as_ptr() as *mut u8, Self::layout(self.len));
if self.len != 0 {
unsafe {
dealloc(self.ptr.as_ptr() as *mut u8, Self::layout(self.len));
}
}
}
}
Expand Down Expand Up @@ -200,7 +202,9 @@ impl<T: Pixel> PlaneData<T> {
}

unsafe fn new_uninitialized(len: usize) -> Self {
let ptr = {
let ptr = if len == 0 {
std::ptr::NonNull::dangling()
} else {
let layout = Self::layout(len);
let ptr = alloc(layout) as *mut T;
if ptr.is_null() {
Expand Down Expand Up @@ -1052,6 +1056,15 @@ pub mod test {

assert_eq!(&output[..64], &plane.data[..64]);
}
#[test]
fn test_plane_zero_len() {
let plane = Plane::<u8>::new(0, 0, 0, 0, 0, 0);
assert_eq!(plane.data.len(), 0);
assert_eq!(*plane.data, []);
let copy = plane.clone();
assert_eq!(copy.data.len(), 0);
assert_eq!(*copy.data, []);
}

#[test]
fn test_plane_downsample() {
Expand Down
Loading