One example where unsafe Rust behaves exactly like C: the optimizer may legally delete your hardware-polling loop, and nothing in the compiler stops you.
Why a formal, statically enforced rule is the only defense.
Direct MMIO dereference is undefined-adjacent territory, so the developer wraps it in unsafe. Compiles clean. Zero warnings.
The read is a non-volatile read: from the optimizer's point of view it has no side effects.
The register is read once, then the loop spins on the cached value regardless of hardware state.
An infinite loop with no side effects may be assumed unreachable and removed entirely.
Result: passes host unit tests, then hangs or skips the wait on target, depending on the optimization level.
Two correct-looking one-liners inside unsafe. The wrong one is a latent field failure.
| Aspect | Requirement |
|---|---|
| Rule | A memory-mapped hardware location shall only be accessed through volatile operations. |
| Category | Mandatory: cannot be permanently waived by team signoff. |
| Rationale | Non-volatile accesses to hardware addresses may be optimized away, hoisted, or cached, producing behavior divergent from the hardware contract. |
| Decidability | Fully statically decidable. |
| Enforcement | Any pointer whose provenance includes an integer-to-pointer cast (as *const / as *mut) shall be dereferenced only via read_volatile/write_volatile-class intrinsics. Direct deref of such pointers is a violation, rejected at build time by a CI lint. |
| Deviation | Permitted only for RAM-backed buffers provably not device memory, documented per deviation request. |
unsafe means "the programmer has manually verified the contract". It marks responsibility; it does not transfer knowledge.
A mandatory rule with a syntactic fingerprint (integer-to-pointer cast feeding a non-volatile deref) that a static check rejects before the build.
The volatile contract is invisible in the code. Only a written, enforced rule can make it visible.
This is why embedded C teams adopted MISRA, and why an unsafe-Rust standard needs the same structure: mandatory rules, static enforcement, formal deviation process.