25.11 Tools for Verifying Unsafe Code

Even with diligent reviews, unsafe code can still harbor memory errors. A valuable tool for detecting such issues is Miri—an interpreter for Rust code that can discover undefined behavior, including:

  • Out-of-bounds memory access
  • Use-after-free errors
  • Invalid deallocation
  • Data races in single-threaded contexts (e.g., dereferencing freed memory)

Another well-known tool for detecting memory-related issues is Valgrind, which can be used with Rust binaries as well.

25.11.1 Installing and Using Miri

Depending on your operating system, Miri may already be installed alongside other Rust tools, or it can be installed via Rustup:

  1. Install Miri (if necessary):

    rustup component add miri
    
  2. Run Miri on your tests:

    cargo miri test
    

Miri interprets your code and flags invalid memory operations, helping you verify that your unsafe code is correct. It can even detect memory leaks caused by cyclic data structures in safe Rust.