Function core::ptr::write_unaligned1.17.0[][src]

pub unsafe fn write_unaligned<T>(dst: *mut T, src: T)

Overwrites a memory location with the given value without reading or dropping the old value.

Unlike write, the pointer may be unaligned.

write_unaligned does not drop the contents of dst. This is safe, but it could leak allocations or resources, so care must be taken not to overwrite an object that should be dropped.

Additionally, it does not drop src. Semantically, src is moved into the location pointed to by dst.

This is appropriate for initializing uninitialized memory, or overwriting memory that has previously been read with read_unaligned.

Safety

Behavior is undefined if any of the following conditions are violated:

Examples

Access fields in a packed struct:

use std::{mem, ptr};

#[repr(packed, C)]
#[derive(Default)]
struct Packed {
    _padding: u8,
    unaligned: u32,
}

let v = 0x01020304;
let mut x: Packed = unsafe { mem::zeroed() };

unsafe {
    // Take a reference to a 32-bit integer which is not aligned.
    let unaligned = &mut x.unaligned;

    // Dereferencing normally will emit an unaligned store instruction,
    // causing undefined behavior.
    // *unaligned = v; // ERROR

    // Instead, use `write_unaligned` to write improperly aligned values.
    ptr::write_unaligned(unaligned, v);
}

// Accessing unaligned values directly is safe.
assert!(x.unaligned == v);Run