For any raw pointer passed as an argument, it is not possible to guarantee its validity. Dereferencing an invalid pointer can lead to undefined
behavior, causing potential segmentation faults or other critical issues. By marking such functions as unsafe
, it notifies the caller
that they need to ensure the pointer’s validity and surround the function call with an unsafe
block to acknowledge the potential risks
involved.
Code examples
Noncompliant code example
pub fn foo(x: *const u8) {
println!("{}", unsafe { *x });
}
// This call "looks" safe but will segfault or worse!
// foo(invalid_ptr);
Compliant solution
pub unsafe fn foo(x: *const u8) {
println!("{}", unsafe { *x });
}
// This would cause a compiler error for calling without `unsafe`
// foo(invalid_ptr);
// Sound call if the caller knows the pointer is valid
unsafe { foo(valid_ptr); }