Rust

Rust

Made by DeepSource

Found redundant use of mem::replace RS-W1114

Bug risk
Major

Using mem::replace(&mut _, mem::uninitialized()) or mem::replace(&mut _, mem::zeroed()) may lead to undefined behaviour even if the value is overwritten later, as the uninitialized value may remain in case of panic recovery.

The take_mut crate offers a sound solution, at the cost of either lazily creating a replacement value or aborting on panic, to ensure that the uninitialized value cannot be observed.

Bad Practice

use std::mem;
fn may_panic(v: Vec<i32>) -> Vec<i32> { v }

#[allow(deprecated, invalid_value)]
fn myfunc (v: &mut Vec<i32>) {
    let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };
    let new_v = may_panic(taken_v); // undefined behavior on panic
    mem::forget(mem::replace(v, new_v));
}

References