Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Does reference `&[MaybeUninit]` that points to an uninitialized memory cause UB?
Does reference `&[MaybeUninit]` that points to an uninitialized memory cause UB?
โ rust ๐ 2025-07-16 ๐ค surdeus ๐๏ธ 2Consider this example:
use std::{alloc::Layout, mem::MaybeUninit};
fn main() {
let layout = Layout::array::<MaybeUninit<u8>>(10).unwrap(); // [MaybeUninit<u8>;10]
unsafe{
let ptr = std::alloc::alloc(layout); // #1
let rf = std::slice::from_raw_parts(ptr, 10); // #2
std::alloc::dealloc(ptr, layout);
}
}
#1
allocated an array of type [MaybeUninit<u8>;10]
, and the memory locations occupied by the array are uninitialized. However, #2
produced a reference to a slice that points to that uninitialized array. However, the reference is of type & [MaybeUninit<u8>]
.
The Rust Reference says:
The Rust compiler assumes that all values produced during program execution are โvalidโ, and producing an invalid value is hence immediate UB.
- [...]
- A reference or
Box<T>
must be aligned and non-null, it cannot be dangling, and it must point to a valid value (in case of dynamically sized types, using the actual dynamic type of the pointee as determined by the metadata). Note that the last point (about pointing to a valid value) remains a subject of some debate.
Since [MaybeUninit<u8>]
is a dynamically sized type, the actual dynamic type of the pointer is [MaybeUninit<u8>;10]
. The uninitialized memory for an array [MaybeUninit<u8>;10]
should be considered as an invalid value. Because the reference does not point to the type MaybeUninit<[MaybeUninit<u8>;10]>
The difference between them here is that the memory occupied by [T; N]
should be initialized such that the value of type [T;N]
is valid; instead, the memory occupied by MaybeUninit<T>
can be uninitialized.
However, I often see some libraries use & [MaybeUninit<u8>]
to denote a piece of uninitialized memory. I test the code under MIRI, and it doesn't report UB. So, what's the reason here? Does my understanding of the cited rules have some deviation?
4 posts - 2 participants
๐ท๏ธ rust_feed