Add a new lint that warns for pointers to stack memory by 1c3t3a · Pull Request #134218 · rust-lang/rust (original) (raw)

Could you explain with what you mean by extremely targeted?

I say targeted because it seems to be exclusively about a syntactic &local expression at the return of a function and I guess I don't expect people to actually write code like that? I also cannot imagine someone writing let foo = *ptr::null(); so this may just be a failure of imagination on my part x).

Mhm I think with enough control flow that adds indirection this can get complicated enough. This PR was motivated by clang having this warning and two weeks after I opened the PR my team found a piece of code that survived for half a year in our codebase and was the perfect motivation for this lint:

// Import actual list from source and use this temporarily for now const GLOBAL: &[&str] = &[ "abcd", ... ];

#[no_mangle] pub extern "C" fn foo() -> *mut *const c_char { let c_strings: Vec<_> = GLOBAL.iter().map(|&val| CString::new(val).unwrap()).collect();

let mut ptrs: Vec<_> = c_strings.iter().map(|cs| cs.as_ptr()).collect();
ptrs.push(std::ptr::null()); // Now safe to push

let boxed_ptrs = ptrs.into_boxed_slice();
let raw_ptr = Box::into_raw(boxed_ptrs);

return raw_ptr as *mut *const c_char;

}

I think this is reasonably indirect to not make it entirely clear what is going on. Especially if you are new to Rust or write FFI code that frequently makes use of raw pointers.

But maybe the fact that we are discussing this is already a sign that it should be a clippy lint? Idk.