The standard Rust library includes a variety of functions for pointer manipulations. Many of these functions require non-null ponter parameters,
including:
-
sym::ptr_read
-
sym::ptr_read_unaligned
-
sym::ptr_read_volatile
-
sym::ptr_replace
-
sym::ptr_write
-
sym::ptr_write_bytes
-
sym::ptr_write_unaligned
-
sym::ptr_write_volatile
-
sym::slice_from_raw_parts
-
sym::slice_from_raw_parts_mut
-
sym::ptr_copy
-
sym::ptr_copy_nonoverlapping
-
sym::ptr_swap
-
sym::ptr_swap_nonoverlapping
Using ptr::null
in unsafe code can result in undefined behavior, compromising the stability and safety of the program. Undefined
behavior occurs when the program does something the Rust language specifications do not define, often leading to crashes or security
vulnerabilities.
Code examples
Noncompliant code example
unsafe { std::slice::from_raw_parts(ptr::null(), 0); } // Noncompliant: Usage of `ptr::null()`.
Compliant solution
unsafe { std::slice::from_raw_parts(NonNull::dangling().as_ptr(), 0); } // Compliant: Uses `NonNull::dangling().as_ptr()` to avoid undefined behavior.