How compiler works with uninitialized memory?
⚓ Rust 📅 2026-05-10 👤 surdeus 👁️ 1I have read many resources about this topic, here a some of them:
- "What The Hardware Does" is not What Your Program Does: Uninitialized Memory
- Here's My Type, So Initialize Me Maybe - Faultlore
- Understanding the basic idea of uninitialized memory - #10 by jorendorff
- Warning I received trying to solve my problem: Clippy Lints
- Answer which confused me even more: How does the compiler understand that memory is initialized? - #2 by derspiny
I'm trying to implement contiguous deque buffer for my program needs where content is placed in the middle of allocated memory. I need to use some internal structure as allocated array for my data. The most straightforward path is to use Vec<u8> and create with vec![0; capacity];. But that is obviously performance - zeroing memory, especially when buffer is reallocated for more space and content is copied.
I found unsafe method set_len on Vec struct and tried to use it right after calling Vec::with_capacity and received warning from clippy. Then I started my investigation about llvm quirks.
The first thing I understood is that I can't use Vec for my purpose, I need some array struct which stores pointer and length.
I need to use my buffer in various scenarios. But the core part is working with network - passing &mut buf[pos..] to AsyncReadExt::read. The way I do this is ensuring data has enough space and then adding x to tail, resulting in data[pos..tail] being uninitialized but valid data which I can write to.
After, I realized I can't do even that. Also I found out that unsafe Rust is not C or C++, it's much more complicated and dangerous place. I learned about MaybeUninit but it can't be used in all places, for example rand::fill.
My question: is there any way to tell the compiler: don't optimize / assume initialized / don't mess up my allocated array without actually writing to it?
10 posts - 3 participants
🏷️ Rust_feed