Unchecked Uninitialized Memory

    Unsafe Rust gives us a powerful tool to handle this problem:mem::uninitialized. This function pretends to return a valuewhen really it does nothing at all. Using it, we can convince Rust that we haveinitialized a variable, allowing us to do trickier things with conditional andincremental initialization.

    Unfortunately, this opens us up to all kinds of problems. Assignment has adifferent meaning to Rust based on whether it believes that a variable isinitialized or not. If it’s believed uninitialized, then Rust will semanticallyjust memcopy the bits over the uninitialized ones, and do nothing else. Howeverif Rust believes a value to be initialized, it will try to Drop the old value!Since we’ve tricked Rust into believing that the value is initialized, we can nolonger safely use normal assignment.

    To handle this, we must use the module. In particular, it providesthree functions that allow us to assign bytes to a location in memory withoutdropping the old value: write, , and .

    It should go without saying that these functions, if misused, will cause serioushavoc or just straight up Undefined Behavior. The only things that thesefunctions themselves require is that the locations you want to read and writeare allocated. However the ways writing arbitrary bits to arbitrarylocations of memory can break things are basically uncountable!

    It’s worth noting that you don’t need to worry about ptr::write-styleshenanigans with types which don’t implement Drop or contain Drop types,because Rust knows not to try to drop them. Similarly you should be able toassign to fields of partially initialized structs directly if those fields don’tcontain any Drop types.

    However when working with uninitialized memory you need to be ever-vigilant forRust trying to drop values you make like this before they’re fully initialized.Every control path through that variable’s scope must initialize the valuebefore it ends, if it has a destructor..

    And that’s about it for working with uninitialized memory! Basically nothinganywhere expects to be handed uninitialized memory, so if you’re going to passit around at all, be sure to be really careful.