]> git.lizzy.rs Git - rust.git/blob - src/docs/mem_replace_with_uninit.txt
[Arithmetic] Consider literals
[rust.git] / src / docs / mem_replace_with_uninit.txt
1 ### What it does
2 Checks for `mem::replace(&mut _, mem::uninitialized())`
3 and `mem::replace(&mut _, mem::zeroed())`.
4
5 ### Why is this bad?
6 This will lead to undefined behavior even if the
7 value is overwritten later, because the uninitialized value may be
8 observed in the case of a panic.
9
10 ### Example
11 ```
12 use std::mem;
13
14 #[allow(deprecated, invalid_value)]
15 fn myfunc (v: &mut Vec<i32>) {
16     let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };
17     let new_v = may_panic(taken_v); // undefined behavior on panic
18     mem::forget(mem::replace(v, new_v));
19 }
20 ```
21
22 The [take_mut](https://docs.rs/take_mut) crate offers a sound solution,
23 at the cost of either lazily creating a replacement value or aborting
24 on panic, to ensure that the uninitialized value cannot be observed.