You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The implementation of the `Vec::extract_if` iterator invokes UB by
always constructing a mutable slice for the entire length of the vector
even though that span of memory can contain holes from items already
drained. The safety contract of `slice::from_raw_parts` requires that
all elements must be properly initialized.
As an example we can look at the following code:
```rust
let mut v = vec![Box::new(0u64), Box::new(1u64)];
for item in v.extract_if(.., |x| **x == 0) {
drop(item);
}
```
In the second iteration a `&mut [Box<u64>]` slice of length 2 will be
constructed. The first slot of the slice contains the bitpattern of an
already deallocated box, causing UB.
This fixes the issue by only creating references to valid items and
using pointer manipulation for the rest. I have also taken the liberty
to remove the big `unsafe` blocks in place of targetted ones with a
SAFETY comment. The approach closely mirrors the implementation of
`Vec::retain_mut`.
Signed-off-by: Petros Angelatos <[email protected]>
0 commit comments