Skip to content

Commit d94bb76

Browse files
committed
Fix dropping elements for zero-sized types in IntoIter
Handle zero-sized types (ZST) to prevent unalignment issues when dropping elements.
1 parent c871d09 commit d94bb76

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

library/alloc/src/vec/into_iter.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -411,15 +411,19 @@ impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
411411
// SAFETY: same as for advance_by()
412412
self.end = unsafe { self.end.sub(step_size) };
413413
}
414-
let to_drop = ptr::slice_from_raw_parts_mut(self.end as *mut T, step_size);
414+
let to_drop = if T::IS_ZST {
415+
// ZST may cause unalignment
416+
ptr::slice_from_raw_parts_mut(ptr::NonNull::<T>::dangling().as_ptr(), step_size)
417+
} else {
418+
ptr::slice_from_raw_parts_mut(self.end as *mut T, step_size)
419+
};
415420
// SAFETY: same as for advance_by()
416421
unsafe {
417422
ptr::drop_in_place(to_drop);
418423
}
419424
NonZero::new(n - step_size).map_or(Ok(()), Err)
420425
}
421426
}
422-
423427
#[stable(feature = "rust1", since = "1.0.0")]
424428
impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {
425429
fn is_empty(&self) -> bool {

tests/ui/iterators/ZST-nthback.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
//@ check-pass
2+
// test Intolter::nth_back does not cause UB for ZSTs with high alignment
3+
4+
#[repr(align(8))]
5+
struct Thing;
6+
7+
fn main() {
8+
let v = vec![Thing, Thing];
9+
let _ = v.into_iter().nth_back(1);
10+
}

0 commit comments

Comments
 (0)