Slice to uninitialized memory

I want to manually allocate a chunk of memory and use it to store an array of pointers (I'm in no_std).
I made such a variable:
static mut SLAB_INFO_PTRS: Once<&'static mut [*mut SlabInfo]> = Once::new();
And now I want to use the pointer to the allocated memory to create a slice using slice::from_raw_parts_mut().
However, I cannot initialize this memory as it is a large amount of memory. The individual elements will be initialized in the future when needed.
But it seems that creating a slice from uninitialized memory is UB, is that right? How can I solve this?

I think it’s sound to make a &mut [MaybeUninit<*mut SlabInfo>] that points to properly-aligned uninitialized memory, as long as you initialize the individual items before calling assume_init_…() on them.

3 Likes

Would this be correct given that the MaybeUninit elements themselves would be uninitialized? After all, they will not be created with MaybeUninit::uninit()

Yes, all that matters is if the type can contain uninitialized bytes.

2 Likes

So I can use an uninitialized chunk of memory and safely create &mut [MaybeUninit<*mut SlabInfo>] from it?

Yes, that is allowed to point to uninitialized memory.