Skip to content

Commit 088fa4a

Browse files
committed
Add section on uninitialized memory
1 parent b40f0b0 commit 088fa4a

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

src/advanced_unsafety/undef_memory.md

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,39 @@
1-
# Undef memory
1+
# Uninitialized memory
2+
3+
> _"I'm Nobody! Who are you? Are you — Nobody — too?"_
4+
> _Emily Dickinson_
5+
6+
While we have covered [invalid values], there's another thing that behaves a lot like invalid values, but has nothing to do with actual bit patterns: Uninitialized memory.
7+
8+
An easy way to think about uninitialized memory is that there's an additional value (often called `undef` using LLVM's term for it) that does not map to any concrete bit pattern, but can be introduced in abstract in various ways, and makes _most_ values invalid.
9+
10+
If you explicitly wish to work with uninitialized and partially-initialized types, [`MaybeUninit<T>`] is a useful abstraction since it can be "initialized" with no overhead and then written to in parts.
11+
12+
## Sources of uninitialized memory
13+
14+
### `mem::uninitialized()`
15+
16+
[`mem::uninitialized()`] is a deprecated API that has a very tempting shape, it lets you do things like `let x = mem::uninitialized()` for cases when you want to construct the value in bits. It's basically _always_ UB to use, since it immediately sets `x` to uninitialized memory, which is UB.
17+
18+
Use [`MaybeUninit<T>`] instead.
19+
20+
### Padding
21+
22+
@@@ Beef up this section
23+
24+
Padding bytes in structs and enums are often but not always uninitialized. This means that treating a struct as a bag of bytes (by, say, treating `&Struct` as `&[u8; size_of::<Struct>()]` and reading from there) is UB even if you don't write invalid values to those bytes, since you are ginning up uninitialized `u8`s.
25+
26+
27+
### Moved-from values
28+
29+
### Freshly allocated memory
30+
31+
32+
## When you might end up making an uninitialized value
33+
34+
## Things you might see if you made an uninitialized value
35+
36+
37+
[invalid values]: ./invalid_values.md
38+
[`mem::uninitialized()`]: https://doc.rust-lang.org/stable/std/mem/fn.uninitialized.html
39+
[`MaybeUninit<T>`]: https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html

0 commit comments

Comments
 (0)