@@ -18,6 +18,7 @@ mod fn_to_numeric_cast_any;
18
18
mod fn_to_numeric_cast_with_truncation;
19
19
mod ptr_as_ptr;
20
20
mod ptr_cast_constness;
21
+ mod ptr_to_temporary;
21
22
mod unnecessary_cast;
22
23
mod utils;
23
24
@@ -657,6 +658,33 @@ declare_clippy_lint! {
657
658
"casting a known floating-point NaN into an integer"
658
659
}
659
660
661
+ declare_clippy_lint ! {
662
+ /// ### What it does
663
+ /// Checks for raw pointers that point to temporary values.
664
+ ///
665
+ /// ### Why is this bad?
666
+ /// Usage of such a pointer can result in Undefined Behavior, as the pointer will stop pointing
667
+ /// to valid stack memory once the temporary is dropped.
668
+ ///
669
+ /// ### Example
670
+ /// ```rust,ignore
671
+ /// const PS: [usize; 3] = [2usize, 3usize, 11usize];
672
+ /// let mut ps = vec![];
673
+ ///
674
+ /// for p in PS {
675
+ /// ps.push(&p as *const usize);
676
+ /// }
677
+ ///
678
+ /// for p in ps {
679
+ /// unsafe { p.read() }; // ⚠️
680
+ /// }
681
+ /// ```
682
+ #[ clippy:: version = "1.72.0" ]
683
+ pub PTR_TO_TEMPORARY ,
684
+ correctness,
685
+ "disallows obtaining a raw pointer to a temporary value"
686
+ }
687
+
660
688
pub struct Casts {
661
689
msrv : Msrv ,
662
690
}
@@ -691,6 +719,7 @@ impl_lint_pass!(Casts => [
691
719
CAST_SLICE_FROM_RAW_PARTS ,
692
720
AS_PTR_CAST_MUT ,
693
721
CAST_NAN_TO_INT ,
722
+ PTR_TO_TEMPORARY ,
694
723
] ) ;
695
724
696
725
impl < ' tcx > LateLintPass < ' tcx > for Casts {
@@ -736,6 +765,7 @@ impl<'tcx> LateLintPass<'tcx> for Casts {
736
765
}
737
766
738
767
as_underscore:: check ( cx, expr, cast_to_hir) ;
768
+ ptr_to_temporary:: check ( cx, expr, cast_expr, cast_to_hir) ;
739
769
740
770
if self . msrv . meets ( msrvs:: BORROW_AS_PTR ) {
741
771
borrow_as_ptr:: check ( cx, expr, cast_expr, cast_to_hir) ;
0 commit comments