@@ -201,6 +201,24 @@ declare_lint! {
201
201
"using 0 as *{const, mut} T"
202
202
}
203
203
204
+ /// **What it does:** Catch casts from `1` to some pointer type
205
+ ///
206
+ /// **Why is this bad?** This generally means a dangling pointer and is better expressed as
207
+ /// {`std`, `core`}`::ptr::`{`dangling`, `dangling_mut`}.
208
+ ///
209
+ /// **Known problems:** None.
210
+ ///
211
+ /// **Example:**
212
+ ///
213
+ /// ```rust
214
+ /// 1 as *const u32
215
+ /// ```
216
+ declare_lint ! {
217
+ pub DANGLING_PTR ,
218
+ Allow ,
219
+ "using 1 as *{const, mut} T"
220
+ }
221
+
204
222
/// **What it does:** Checks for (in-)equality comparisons on floating-point
205
223
/// value and constant, except in functions called `*eq*` (which probably
206
224
/// implement equality for a type involving floats).
@@ -237,6 +255,7 @@ impl LintPass for Pass {
237
255
USED_UNDERSCORE_BINDING ,
238
256
SHORT_CIRCUIT_STATEMENT ,
239
257
ZERO_PTR ,
258
+ DANGLING_PTR ,
240
259
FLOAT_CMP_CONST
241
260
)
242
261
}
@@ -628,14 +647,21 @@ fn check_cast(cx: &LateContext, span: Span, e: &Expr, ty: &Ty) {
628
647
if let TyPtr ( MutTy { mutbl, .. } ) = ty. node;
629
648
if let ExprLit ( ref lit) = e. node;
630
649
if let LitKind :: Int ( value, ..) = lit. node;
631
- if value == 0 ;
632
650
if !in_constant( cx, e. id) ;
633
651
then {
634
- let msg = match mutbl {
635
- Mutability :: MutMutable => "`0 as *mut _` detected. Consider using `ptr::null_mut()`" ,
636
- Mutability :: MutImmutable => "`0 as *const _` detected. Consider using `ptr::null()`" ,
637
- } ;
638
- span_lint( cx, ZERO_PTR , span, msg) ;
652
+ if value == 0 {
653
+ let msg = match mutbl {
654
+ Mutability :: MutMutable => "`0 as *mut _` detected. Consider using `ptr::null_mut()`" ,
655
+ Mutability :: MutImmutable => "`0 as *const _` detected. Consider using `ptr::null()`" ,
656
+ } ;
657
+ span_lint( cx, ZERO_PTR , span, msg) ;
658
+ } else if value == 1 {
659
+ let msg = match mutbl {
660
+ Mutability :: MutMutable => "`1 as *mut _` detected. Consider using `ptr::dangling_mut()`" ,
661
+ Mutability :: MutImmutable => "`1 as *const _` detected. Consider using `ptr::dangling()`" ,
662
+ } ;
663
+ span_lint( cx, DANGLING_PTR , span, msg) ;
664
+ }
639
665
}
640
666
}
641
667
}
0 commit comments