An unsafe block marks operations whose safety requires programmer verification. It permits operations such as raw-pointer dereferencing, calling unsafe functions, and accessing mutable statics. It does not turn off the borrow checker, type system, or other checks. section 5.2.1 section 7.1.3
Treat each block as a promise that the required invariants hold. Audit it carefully, and isolate unsafe operations behind safe abstractions where possible. section 5.2.1
const GPIOA_ODR: *mut u32 = 0x4001_080C as *mut u32;
// More code
unsafe {
*GPIOA_ODR = 0x0000_0001;
}
Creating the raw pointer is allowed outside the block; dereferencing it requires unsafe. The programmer must verify the register address, alignment, accessibility, and type. section 5.2.2
A plain pointer dereference is not guaranteed to perform a volatile memory-mapped I/O access: optimization may remove, merge, or reorder it. Use explicit volatile operations or a PAC/HAL API for registers. A full-register write can also overwrite unrelated bits. section 5.2.2
static mut SHARED: u32 = 0;
fn main() -> ! {
loop {
unsafe { SHARED += 1; } // Unsafe: may introduce race conditions
}
}
#[interrupt]
fn SysTick() {
unsafe { SHARED += 1; } // Unsafe: may introduce race conditions
}
Both the main loop and interrupt handler update the same mutable static. Unsafe permits the accesses but does not prevent a race; prefer safer sharing methods unless exclusive access can be guaranteed. section 4.6.1
extern crate alloc;
use alloc::alloc::{alloc, dealloc, Layout};
fn manual_heap_example() {
// Describe what we want: size and alignment of a u32.
let layout = Layout::new::<u32>();
unsafe {
let ptr = alloc(layout);
if ptr.is_null() {
// Allocation failed; bail out before dereferencing.
return;
}
// Write, then read back.
*(ptr as *mut u32) = 1986;
assert_eq!(*(ptr as *mut u32), 1986);
// Deallocate using the same layout we allocated with.
dealloc(ptr, layout);
}
}
Manual allocation requires a null check before dereferencing and the same layout for deallocation. Box::new provides an alternative that handles these details automatically. section 7.1.3
Calls to generated C bindings also require unsafe. A thin safe wrapper can keep those calls localized, provided it upholds their requirements. section 8.5.2



