capypad
0 day streak
rust / intermediate
Snippet

Unsafe Rust: Manual Pointer Operations

Unsafe blocks in Rust unlock five additional capabilities: raw pointer dereferencing, calling unsafe functions, accessing mutable static variables, implementing unsafe traits, and modifying raw arrays. These operations bypass the borrow checker and are typically used for low-level operations like FFI, custom allocators, or interacting with hardware. While powerful, unsafe code remains isolated—the compiler still ensures memory safety for safe Rust code interacting with unsafe blocks.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
unsafe fn danger_zone() {
let mut value = 42i32;
let ptr = &mut value as *mut i32;
println!("Original: {}", value);
*ptr = 100;
println!("Modified via pointer: {}", value);
}
 
unsafe fn raw_slice_access() {
let arr = [1, 2, 3, 4, 5];
let ptr = arr.as_ptr();
let third = ptr.offset(2).read();
println!("Third element: {}", third);
}
 
unsafe fn reinterprete_memory() {
let num: u32 = 0x41424344; // ASCII: DCBA
let bytes: &[u8; 4] = unsafe { std::mem::transmute(&num) };
println!("Bytes: {:02x} {:02x} {:02x} {:02x}",
bytes[0], bytes[1], bytes[2], bytes[3]);
}
 
fn main() {
unsafe {
danger_zone();
raw_slice_access();
reinterprete_memory();
}
println!("Unsafe code completed successfully");
}
Breakdown
1
*mut i32
Raw mutable pointer type, untracked by borrow checker
2
ptr.offset(2)
Pointer arithmetic to access third element
3
.read()
Read value from raw pointer without borrowing
4
std::mem::transmute
Bit-level type reinterpretation, requires unsafe
5
unsafe { }
Required wrapper for unsafe operations