-
Notifications
You must be signed in to change notification settings - Fork 13.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add lint to detect dereferencing of NULL pointers #83856
Comments
Ah, turns out clippy already has a lint for this: |
@rustbot claim |
@ABouttefeux awesome. :) Let me know if you need any help. |
Thanks :) |
Did you mean something slightly different with your "okay in contexts like" examples, perhaps? Neither of those two actually compile as written, since they're just attempts to deference something that isn't even a pointer. You get: error[E0614]: type `usize` cannot be dereferenced in both cases. |
oops I screwed up the casts, should be fixed now. |
Yeah, happy to have Clippy lints upstreamed to rust, let us know when it's done so we can deprecate it on our end |
@RalfJung for detecting a call like |
You first need to add the diagnostic item attribute to the relevant function inside rust/library/core/src/mem/mod.rs Line 621 in 58e7189
This name must be globally unique, e.g. Then you add those names to the list in |
…alfJung add lint deref_nullptr detecting when a null ptr is dereferenced fixes rust-lang#83856 changelog: add lint that detect code like ```rust unsafe { &*core::ptr::null::<i32>() }; unsafe { addr_of!(std::ptr::null::<i32>()) }; let x: i32 = unsafe {*core::ptr::null()}; let x: i32 = unsafe {*core::ptr::null_mut()}; unsafe {*(0 as *const i32)}; unsafe {*(core::ptr::null() as *const i32)}; ``` ``` warning: Dereferencing a null pointer causes undefined behavior --> src\main.rs:5:26 | 5 | let x: i32 = unsafe {*core::ptr::null()}; | ^^^^^^^^^^^^^^^^^^ | | | a null pointer is dereferenced | this code causes undefined behavior when executed | = note: `#[warn(deref_nullptr)]` on by default ``` Limitation: It does not detect code like ```rust const ZERO: usize = 0; unsafe {*(ZERO as *const i32)}; ``` or code where `0` is not directly a literal
I propose we add a lint that detects code like
Some people seem to think that this is okay in contexts like
&*(0 as *const i32)
oraddr_of!(*(0 as *const i32))
, but that is not the case --*
on a NULL pointer is UB even as a place expression.To implement this, you can use the
invalid_value
lint as a template:rust/compiler/rustc_lint/src/builtin.rs
Line 2360 in 9d8f833
check_expr
should check forUnary
expressions with aDeref
operator, and then check the operand to be either a cast of0
to a pointer type, or a call to one of thenull
methods. To detect the methods, make them "diagnostic items"; theinvalid_value
lint does that e.g. formem::zeroed
so it can again serve as a template here.The text was updated successfully, but these errors were encountered: