Calling Unsafe Functions
Failing to uphold the safety requirements breaks memory safety!
Always include a safety comment for each unsafe
block. It must explain why the
code is actually safe. This example is missing a safety comment and is unsound.
Speaker Notes
Key points:
- The second argument to
slice::from_raw_parts
is the number of elements, not bytes! This example demonstrates unexpected behavior by reading past the end of one array and into another. - This is undefined behavior because we’re reading past the end of the array that the pointer was derived from.
log_public_key
should be unsafe, becausepk_ptr
must meet certain prerequisites to avoid undefined behaviour. A safe function which can cause undefined behaviour is said to beunsound
. What should its safety documentation say?- The standard library contains many low-level unsafe functions. Prefer the safe alternatives when possible!
- If you use an unsafe function as an optimization, make sure to add a benchmark to demonstrate the gain.