Unsafe Rust Code

last updated Oct 06, 2021

Rust has a feature that doesn’t enfore memory safey at compile time and it’s what is refered to as unsafe rust. By default rust compiler reject any program that doesn’t sure it enough to be memory safe. unsafe rust code give capabilities to a programmer to write code that compiler doesn’t check memory safefty for. if you use unsafe code incorrectly, some problems can happen like null pointer deferencing.

Underlying hardware code is unsafe, if rust didn’t allow you to write unsafe code you can’t be able to do systems programming with it.

Unsafe rust gives you additional powers like.

  1. Dereference a raw pointer
  2. Call an unsafe function or method
  3. Implement an unsafe trait
  4. Access fields of unions

Though unsafe rust give’s you those superpowers. It doesn’t disable the borrow checker or any other rust type safety. You should always enclose unsafe code into a safe block since it prevents uses of unsafe from leaking all other places. Using safe abstraction is safe.

Dereference a raw pointer

Rust compiler ensures that references are always valid. unsafe rust has a new type called raw pointers that are similar to references. like references raw pointers can be immutable and mutable. There are written like *const T and *mut T respectively. In context of raw pointers, immutable means that a pointer cann’t be directly assigned to after being dereferenced.

We can create raw pointers in safe block; we just can’t dereference raw pointers outside an unsafe block and read data pointed to.

fn main() {
    let mut number = 10;

    let rw_pointer = &number as *const i32;
    let another_mut_rw_pointer = &mut number as *mut i32;

    unsafe {
        println!("r1 is: {}", *rw_pointer);
        println!("r2 is: {}", *another_mut_rw_pointer);

With raw pointers we are allowed to create mutable and immutable reference from a mutable variable. Raw pointers are used when calling c code.

Calling an Unsafe Function or Method

Unsafe block is also required when we want to call unsafe functions or methods. The unsafe keyword on functions and methods indicates that it has requirements that we need to take care of before calling it.

Creating safe abstraction over unsafe code

It’s very common to wrap unsafe code into a safe function.

Accessing or modifying a mutable static variable

Global variables in Rust are called static variables. Constants and immutable static variables are similar,a small difference is that as a static variable have a fixed address in memory. using the value will always acess the same data. constants are allowed to suplicate their data whenever they are used. Static variables can be mutable, but accessing mutable static variables is unsafe.