Function std::ptr::write_unaligned

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 should 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.


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

  • dst must be valid for writes.

Note that even if T has size 0, the pointer must be non-NULL.


Access fields in a packed struct:

use std::{mem, ptr};

#[repr(packed, C)]
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 as *mut u32;

    // Dereferencing normally will emit an aligned store instruction,
    // causing undefined behavior because the pointer is not aligned.
    // *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);

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.