@@ -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,31 @@ 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+ /// It will result in Undefined Behavior, as the pointer will stop pointing to valid stack
667+ /// memory once the temporary is dropped.
668+ ///
669+ /// ### Example
670+ /// ```rust,ignore
671+ /// let p = &0u32 as *const u32;
672+ /// unsafe { p.read() }; // ⚠️
673+ /// ```
674+ /// Use instead:
675+ /// ```rust,ignore
676+ /// let x = 0u32;
677+ /// let px = &x as *const u32;
678+ /// unsafe { px.read() };
679+ /// ```
680+ #[ clippy:: version = "1.72.0" ]
681+ pub PTR_TO_TEMPORARY ,
682+ correctness,
683+ "disallows obtaining a raw pointer to a temporary value"
684+ }
685+
660686pub struct Casts {
661687 msrv : Msrv ,
662688}
@@ -691,6 +717,7 @@ impl_lint_pass!(Casts => [
691717 CAST_SLICE_FROM_RAW_PARTS ,
692718 AS_PTR_CAST_MUT ,
693719 CAST_NAN_TO_INT ,
720+ PTR_TO_TEMPORARY ,
694721] ) ;
695722
696723impl < ' tcx > LateLintPass < ' tcx > for Casts {
@@ -736,6 +763,7 @@ impl<'tcx> LateLintPass<'tcx> for Casts {
736763 }
737764
738765 as_underscore:: check ( cx, expr, cast_to_hir) ;
766+ ptr_to_temporary:: check ( cx, expr, cast_expr, cast_to_hir) ;
739767
740768 if self . msrv . meets ( msrvs:: BORROW_AS_PTR ) {
741769 borrow_as_ptr:: check ( cx, expr, cast_expr, cast_to_hir) ;
0 commit comments