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)
}

Remediation

Represent absence with Option<&T> or Option<fn()>, which is null-pointer-optimised and therefore costs nothing extra. When a raw pointer really is needed, keep it as *const T and check it with is_null() before converting via NonNull::new or as_ref().

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved