Working with Unsafe Code in Rust

Sterling Cobb
3 min readJan 24, 2023

Rust is a systems programming language that prides itself on its safety features, such as memory safety and data race prevention. However, there are certain situations where the use of unsafe code may be necessary, such as when interfacing with C libraries or when performance optimization is a priority. In this article, we will explore the use of unsafe code in Rust, including examples, best practices, and different contexts in which it may be used.

Examples of Unsafe Code in Rust

One common use case for unsafe code in Rust is when interfacing with C libraries. For example, let’s say we have a C function that takes a pointer to a mutable string and modifies it in place. In Rust, we would need to use the extern keyword to declare the function and the unsafe keyword to indicate that we are working with unsafe code. Here is an example:

extern "C" {
fn modify_string(s: *mut c_char);
}

fn main() {
let mut s = "Hello, world!".to_string();
let s_ptr = s.as_mut_ptr();
unsafe {
modify_string(s_ptr);
}
println!("{}", s);
}

Another example of unsafe code in Rust is when working with raw pointers. For example, let’s say we want to manually deallocate memory that was allocated on the heap. We can use the std::ptr module to perform this task, but it requires the use of the unsafe keyword. Here is an example:

use std::ptr;

fn main() {
let mut x = Box::new(5);
let x_ptr = &mut *x as *mut i32;
unsafe {…

--

--