BorrowCheck › Rust language core

Unsafe, UB, FFI

Raw pointers, the unsafe contract, the UB catalog, repr and ABI, extern "C", checking with Miri.

The topic explains what an unsafe block permits and what responsibility it shifts to the author: the compiler stops checking only a few operations, while the borrow checker keeps working. The questions on raw pointers check how a pointer differs from a reference, why add steps by elements rather than bytes, how wrapping_add differs from add, what &raw mut is for, and why a slice pointer is two words wide. The subtopic on the contract covers safe wrappers around unsafe, unsound functions, unsafe traits and attributes, as well as extern blocks and safe functions in edition 2024. The catalog of undefined behavior covers invalid bit patterns, reading uninitialized memory through MaybeUninit, writing through a cast &T, unreachable_unchecked, and what does not count as UB. The subtopics on repr and FFI explain what repr(C), repr(transparent) and repr(packed) guarantee, why a reference to a packed field is forbidden, which types can cross the extern "C" boundary, and what happens to a panic at that boundary. The last subtopic shows which errors Miri detects, such as access to memory after reallocation, and where the limits of its applicability lie.

44 questions: 18 basic, 23 intermediate, 3 advanced. 6 info pages, 26 sources.

Subtopics

  1. Raw pointers
  2. The unsafe contract
  3. The UB catalog
  4. repr and ABI
  5. FFI and extern "C"
  6. Checking with Miri

Previous: Async · Next: Macros