Skip to content

Commit 9063b64

Browse files
committed
Fix zero-sized reference to deallocated memory
fixes #91772
1 parent 4a66a70 commit 9063b64

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

library/alloc/src/vec/drain.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -128,10 +128,6 @@ impl<T, A: Allocator> Drop for Drain<'_, T, A> {
128128

129129
let iter = mem::replace(&mut self.iter, (&mut []).iter());
130130
let drop_len = iter.len();
131-
let drop_ptr = iter.as_slice().as_ptr();
132-
133-
// forget iter so there's no aliasing reference
134-
drop(iter);
135131

136132
let mut vec = self.vec;
137133

@@ -155,6 +151,12 @@ impl<T, A: Allocator> Drop for Drain<'_, T, A> {
155151
return;
156152
}
157153

154+
// as_slice() must only be called when iter.len() is > 0 because
155+
// vec::Splice modifies vec::Drain fields and may grow the vec which would invalidate
156+
// the iterator's internal pointers. Creating a reference to deallocated memory
157+
// is invalid even when it is zero-length
158+
let drop_ptr = iter.as_slice().as_ptr();
159+
158160
unsafe {
159161
// drop_ptr comes from a slice::Iter which only gives us a &[T] but for drop_in_place
160162
// a pointer with mutable provenance is necessary. Therefore we must reconstruct

0 commit comments

Comments
 (0)