Is it UB to read uninitialized memory from another process via shared memory?

⚓ Rust    📅 2026-01-25    👤 surdeus    👁️ 1      

surdeus

Imagine this setup:

  • Two processes share a memory region created via shm_open + mmap (or similar).
  • In process A, I have some uninitialized memory.
  • I copy its raw bytes into the shared memory.
  • In process B, I read those bytes and treat them as opaque data (e.g. write them to a file), without interpreting them as a Rust value.

Example Process A:

// process A (writer)
use std::mem::MaybeUninit;
use std::ptr;

let src: [MaybeUninit<u8>; 1024] = [MaybeUninit::uninit(); 1024];

unsafe {
    // shared_mem_ptr: *mut MaybeUninit<u8> points into the mmap'd shared region
    ptr::copy_nonoverlapping(src.as_ptr(), shared_mem_ptr, 1024);
}

Example Process B:

// process B (reader)
unsafe {
    // shared_mem_ptr: *const u8 pointing into the same shared region
    let bytes = std::slice::from_raw_parts(shared_mem_ptr, 1024);
    std::fs::write("dump.bin", bytes).unwrap();
}

Now, here is my line of thinking:

  1. Whatever the process A is doing is perfectly legal, you are allowed to use ptr::copy_nonoverlapping with uninitialized memory per the answer to Is it UB to byte-copy memory containing repr(C) structs with padding?
  2. There is no way for reader to know whether the part of RAM it is reading is or isn't uninitialized memory, hence it seems impossible for compiler to create UB in this case.

Am I missing anything? Can this really go wrong in any way?

6 posts - 5 participants

Read full topic

🏷️ Rust_feed