Null pointer built by casting the literal zero instead of using ptr::null

ID

rust.maintainability.std_ptr_null_denote_null

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Idiomatic Usage

Language

Rust

Description

Detects a null raw pointer written as a cast of the integer literal zero, such as 0 as *const T or 0usize as *mut T, where std::ptr::null() or std::ptr::null_mut() is the intended spelling.

Rationale

The cast form reads as arithmetic on an address, so it is indistinguishable at a glance from a real integer-to-pointer conversion, and grep cannot separate the two when the null cases need auditing. It also leaves the pointee type to inference, which means a change elsewhere can silently repoint the pointer at a different type without the line changing.

The following code illustrates the pattern detected by this rule:

use std::ptr;
pub fn handles() -> (*const u8, *mut i32, *const core::ffi::c_void) {
    // FLAGGED: Null pointer built by casting the literal zero instead of using ptr::null
    let a = 0 as *const u8;
    // FLAGGED: Null pointer built by casting the literal zero instead of using ptr::null
    let b = 0 as *mut i32;
    // FLAGGED: Null pointer built by casting the literal zero instead of using ptr::null
    let c = 0usize as *const core::ffi::c_void;
    (a, b, c)
}

Remediation

Use std::ptr::null::<T>() or std::ptr::null_mut::<T>(), which names the intent and pins the pointee type. Where the pointer may be absent, prefer Option<&T> or Option<NonNull<T>>, which make the null case impossible to dereference by mistake.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved