What Unsafe Rust Can Do

    • Dereference raw pointers
    • Call functions (including C functions, compiler intrinsics, and the raw allocator)
    • Implement unsafe traits
    • Mutate statics
    • Access fields of s

    That’s it. The reason these operations are relegated to Unsafe is that misusingany of these things will cause the ever dreaded Undefined Behavior. InvokingUndefined Behavior gives the compiler full rights to do arbitrarily bad thingsto your program. You definitely should not invoke Undefined Behavior.

    • Dereferencing null, dangling, or unaligned pointers
    • Reading uninitialized memory
    • Producing invalid primitive values:
      • dangling/null references
      • null fn pointers
      • a that isn’t 0 or 1
      • an undefined enum discriminant
      • a outside the ranges [0x0, 0xD7FF] and [0xE000, 0x10FFFF]
      • A non-utf8 str
    • Causing a

    That’s it. That’s all the causes of Undefined Behavior baked into Rust. Ofcourse, unsafe functions and traits are free to declare arbitrary otherconstraints that a program must maintain to avoid Undefined Behavior. Forinstance, the allocator APIs declare that deallocating unallocated memory isUndefined Behavior.

    Rust is otherwise quite permissive with respect to other dubious operations.Rust considers it “safe” to:

    • Deadlock
    • Have a race condition
    • Leak memory
    • Fail to call destructors
    • Overflow integers
    • Abort the program