Skip to content

dangling_pointers_from_temporaries lint does not warn when as_ptr() result escapes function #139249

Closed as duplicate of#78691
@alex

Description

@alex

Consider this basic dangling pointer from a temporary:

use std::ffi::CString;

unsafe extern "C" {
    fn g(v: *const i8);
}

pub fn f1(s: &str) {
    let p = CString::new(s).unwrap().as_ptr();
    unsafe { g(p); }
}

It produces a warning. Very good.

However, if instead we have an Option<&str> and we use some Option methods to convert it to a pointer, we no longer get a warning:

use std::ptr;
use std::ffi::CString;

unsafe extern "C" {
    fn g(v: *const i8);
}

pub fn f2(s: Option<&str>) {
    let p = s.map(|v| CString::new(v).unwrap()).map_or(ptr::null(), |v| v.as_ptr());
    unsafe { g(p); }
}

I believe the closure passed to map_or should be triggering the warning: it takes Option<CString> as an argument, it calls as_ptr(), it drops the Option<CString>, and then it makes use of the pointer (to return it).

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.L-dangling_pointers_from_temporariesLint: dangling_pointers_from_temporariesL-false-negativeLint: False negative (should have fired but didn't).T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions