RS.CLIPPY.MEM_REPLACE_WITH_UNINIT
`mem::replace(&mut _, mem::uninitialized())` or `mem::replace(&mut _, mem::zeroed())`
This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: mem_replace_with_uninit. Copyright ©2025 The Rust Team. All rights reserved.
What it does
Checks for mem::replace(&mut _, mem::uninitialized())
and mem::replace(&mut _, mem::zeroed()).
Why is this bad?
This will lead to undefined behavior even if the value is overwritten later, because the uninitialized value may be observed in the case of a panic.
Example
use std::mem;
#[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));
}
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.