Null pointer transmuted into a reference or function pointer
ID |
rust.correctness.null_pointers_transmuted |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Undefined Behaviour |
Language |
Rust |
Description
Detects mem::transmute calls whose argument is a null pointer, written either as the literal 0 or as ptr::null() / ptr::null_mut().
Rationale
References and function pointers are non-null by definition, and the compiler relies on that invariant when it optimises. Producing one from a null pointer is immediate undefined behaviour, so the program can misbehave long before anything is dereferenced.
The following code illustrates the pattern detected by this rule:
use std::mem;
use std::ptr;
type Callback = extern "C" fn(i32) -> i32;
unsafe fn build_callbacks() -> (Callback, Callback, Callback) {
// FLAGGED: Null pointer transmuted into a reference or function pointer
let a: Callback = std::mem::transmute(0usize);
// FLAGGED: Null pointer transmuted into a reference or function pointer
let b: Callback = mem::transmute(0);
// FLAGGED: Null pointer transmuted into a reference or function pointer
let c: Callback = transmute(0_isize);
(a, b, c)
}