• Wed. Oct 23rd, 2024

Safety off: Programming in Rust with `unsafe`

Byadmin

Jul 12, 2024



extern “C” {
fn abs(input: i32) -> i32;
}

fn main() {
unsafe {
println!(“Absolute value of -3 according to C: {}”, abs(-3));
}
}

Any calls made to the functions exposed via the extern “C” block must be wrapped in unsafe, the better to ensure you take proper responsibility for what you send to it and get back from it.
Altering mutable static variables
Global or static variables in Rust can be set to mutable, since they occupy a fixed memory address. However, it’s only possible to modify a mutable static variable inside an unsafe block.
Data races are the biggest reason you need unsafe to alter mutable static variables. You’d get unpredictable results if you allowed the same mutable static variable to be modified from different threads. So, while you can use unsafe to make such changes, any data race issues would be your responsibility, not Rust’s. In general, Rust cannot entirely prevent data races, but you need to be doubly cautious about that in unsafe blocks.



Source link