What Is Undefined Behavior in Rust?

Undefined behavior in Rust is unpredictable program execution caused by violating memory safety rules, often occurring in unsafe code blocks.

Undefined behavior in Rust occurs when code violates memory safety rules, such as accessing invalid memory or data races, causing the program to crash or behave unpredictably. This typically happens in unsafe blocks where the compiler skips checks, like when multiple threads access a static mut variable without synchronization.

static mut COUNTER: u32 = 0;

/// SAFETY: Calling this from more than a single thread at a time is undefined
/// behavior, so you *must* guarantee you only call it from a single thread at
/// a time.
unsafe fn add_to_count(inc: u32) {
    unsafe {
        COUNTER += inc;
    }
}

In this example, calling add_to_count from multiple threads simultaneously creates a data race, which is undefined behavior.