EGV rust ffi_error ai_generated true

SIGSEGV: segmentation fault accessing null pointer via FFI call

ID: rust/rust-ffi-null-pointer

Also available as: JSON · Markdown
78%Fix Rate
82%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

FFI functions returned or received a null pointer that was dereferenced without checking. Always validate pointers at FFI boundaries.

generic

Workarounds

  1. 88% success Use NonNull or Option<NonNull> for FFI pointer types
    use std::ptr::NonNull;
    let ptr = NonNull::new(unsafe { ffi_function() })
        .ok_or("FFI returned null")?;

    Sources: https://doc.rust-lang.org/std/ptr/struct.NonNull.html

  2. 85% success Wrap FFI calls in a safe Rust API that validates all pointers
    pub fn safe_wrapper() -> Result<SafeType, Error> {
        let raw = unsafe { ffi_call() };
        if raw.is_null() { return Err(Error::NullPointer); }
        Ok(unsafe { SafeType::from_raw(raw) })
    }

    Sources: https://doc.rust-lang.org/nomicon/ffi.html

Dead Ends

Common approaches that don't work:

  1. Ignore the null check because the C library 'should never return null' 90% fail

    C libraries return null on error conditions; assuming non-null leads to segfaults

Error Chain

Leads to:
Preceded by:
Frequently confused with: