@@ -18,6 +18,7 @@ mod fn_to_numeric_cast_any;
1818mod fn_to_numeric_cast_with_truncation;
1919mod ptr_as_ptr;
2020mod ptr_cast_constness;
21+ mod ptr_to_temporary;
2122mod unnecessary_cast;
2223mod utils;
2324
@@ -657,6 +658,33 @@ declare_clippy_lint! {
657658 "casting a known floating-point NaN into an integer"
658659}
659660
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+
660688pub struct Casts {
661689 msrv : Msrv ,
662690}
@@ -691,6 +719,7 @@ impl_lint_pass!(Casts => [
691719 CAST_SLICE_FROM_RAW_PARTS ,
692720 AS_PTR_CAST_MUT ,
693721 CAST_NAN_TO_INT ,
722+ PTR_TO_TEMPORARY ,
694723] ) ;
695724
696725impl < ' tcx > LateLintPass < ' tcx > for Casts {
@@ -736,6 +765,7 @@ impl<'tcx> LateLintPass<'tcx> for Casts {
736765 }
737766
738767 as_underscore:: check ( cx, expr, cast_to_hir) ;
768+ ptr_to_temporary:: check ( cx, expr, cast_expr, cast_to_hir) ;
739769
740770 if self . msrv . meets ( msrvs:: BORROW_AS_PTR ) {
741771 borrow_as_ptr:: check ( cx, expr, cast_expr, cast_to_hir) ;
0 commit comments