Skip to content

Docs for MaybeUninit::assume_init should indicate that reading uninit POD isn't sound #150689

@tgross35

Description

@tgross35

The question about whether or not it is sound to read uninit data if it's an integer or other POD comes up from time to time. I think it's worth pointing this out in the MaybeUninit docs since that's probably the entrypoint for such a problem to come up, and currently the docs only mention Vec https://doc.rust-lang.org/nightly/std/mem/union.MaybeUninit.html#method.assume_init.

For reference:

use std::mem::MaybeUninit;

fn main() {
    let x = MaybeUninit::<u8>::uninit();
    let _ = unsafe { x.assume_init() };
}
error: Undefined Behavior: reading memory at alloc214[0x0..0x1], but memory is uninitialized at [0x0..0x1], and this operation requires initialized memory
 --> src/main.rs:5:22
  |
5 |     let _ = unsafe { x.assume_init() };
  |                      ^^^^^^^^^^^^^^^ Undefined Behavior occurred here
  |
  = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
  = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information

Uninitialized memory occurred at alloc214[0x0..0x1], in this allocation:
alloc214 (stack variable, size: 1, align: 1) {
    __                                              │ ░
}

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace

Iirc we don't have a way to make this kind of behavior sound either without going via assembly.

Cc @RalfJung

Metadata

Metadata

Assignees

Labels

A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-enhancementCategory: An issue proposing an enhancement or a PR with one.E-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.Libs-SmallLibs issues that are considered "small" or self-containedT-libsRelevant to the library team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions