Skip to content

Commit

Permalink
Fix zero-sized reference to deallocated memory
Browse files Browse the repository at this point in the history
fixes #91772
  • Loading branch information
the8472 committed Dec 11, 2021
1 parent 4a66a70 commit 9063b64
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions library/alloc/src/vec/drain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,6 @@ impl<T, A: Allocator> Drop for Drain<'_, T, A> {

let iter = mem::replace(&mut self.iter, (&mut []).iter());
let drop_len = iter.len();
let drop_ptr = iter.as_slice().as_ptr();

// forget iter so there's no aliasing reference
drop(iter);

let mut vec = self.vec;

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

// as_slice() must only be called when iter.len() is > 0 because
// vec::Splice modifies vec::Drain fields and may grow the vec which would invalidate
// the iterator's internal pointers. Creating a reference to deallocated memory
// is invalid even when it is zero-length
let drop_ptr = iter.as_slice().as_ptr();

unsafe {
// drop_ptr comes from a slice::Iter which only gives us a &[T] but for drop_in_place
// a pointer with mutable provenance is necessary. Therefore we must reconstruct
Expand Down

0 comments on commit 9063b64

Please sign in to comment.