What are examples of times when unsafe code is needed?

I've heard unsafe code is needed and cannot be worked around for building operating systems for example.

Do you have any concrete examples of times unsafe code is needed?

1 Like

If you are writing an operating system you are going to need to write to and read from registers in actual hardware devices. These registers are usually mapped to some address in memory. No programming language can know if those registers are where you say they are, or what type of data they hold or how the data they hold changes when the hardware is doing the changes. Therefore Rust cannot know how to verify your use of such registers. Ergo you need to turn off some checking with "unsafe".

A similar situation arises when you are using Rust together with some other language, linked into the same program. Rust cannot know what is going on in the code that other language has generated, so once again "unsafe" is required.

A small amount of "unsafe" is also required to create some commonly used data structures as seen in Rust libraries.

4 Likes

To make the Vec type, for example. It needs to be able to allocate a buffer of uninitialized memory.

split_at_mut() and mutable iterators need to use use unsafe. Safe Rust can't have two exclusive references that point to the same memory, but the borrow checker is too simplistic to analyze code of multiple slicing operations or iterator implementations to prove they never do that.

Rust is built around a concept of building safe abstractions on top of unsafe code. So unsafe is pretty much everywhere in implementation of basic building blocks, and only code on top of these building blocks is safe.

3 Likes