Skip to content

Commit 3949157

Browse files
committed
instantly_dangling_pointer: add documentation
1 parent e2f6c80 commit 3949157

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

compiler/rustc_lint/src/dangling.rs

+36-2
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,42 @@ declare_lint! {
3535
// FIXME: does not catch UnsafeCell::get
3636
// FIXME: does not catch getting a ref to a temporary and then converting it to a ptr
3737
declare_lint! {
38-
/// TODO
38+
/// The `instantly_dangling_pointer` lint detects getting a pointer to data
39+
/// of a temporary that will immediately get dropped.
40+
///
41+
/// ### Example
42+
///
43+
/// ```rust
44+
/// # #![allow(unused)]
45+
/// # unsafe fn use_data(ptr: *const u8) {
46+
/// # dbg!(unsafe { ptr.read() });
47+
/// # }
48+
/// fn gather_and_use(bytes: impl Iterator<Item = u8>) {
49+
/// let x: *const u8 = bytes.collect::<Vec<u8>>().as_ptr();
50+
/// unsafe { use_data(x) }
51+
/// }
52+
/// ```
53+
///
54+
/// {{produces}}
55+
///
56+
/// ### Explanation
57+
///
58+
/// Getting a pointer from a temporary value will not prolong its lifetime,
59+
/// which means that the value can be dropped and the allocation freed
60+
/// while the pointer still exists, making the pointer dangling.
61+
/// This is not an error (as far as the type system is concerned)
62+
/// but probably is not what the user intended either.
63+
///
64+
/// If you need stronger guarantees, consider using references instead,
65+
/// as they are statically verified by the borrow-checker to never dangle.
66+
///
67+
/// Note: This lint does **not** get triggered by methods & functions
68+
/// that intentionally produce dangling pointers, such as:
69+
///
70+
/// - `core::ptr::dangling` & `core::ptr::dangling_mut`
71+
/// - `core::ptr::NonNull::dangling`
72+
/// - `std::alloc::Layout::dangling`
73+
///
3974
pub INSTANTLY_DANGLING_POINTER,
4075
Warn,
4176
"detects getting a pointer that will immediately dangle"
@@ -100,7 +135,6 @@ fn is_temporary_rvalue(expr: &Expr<'_>) -> bool {
100135
// Calls return rvalues.
101136
ExprKind::Call(..) | ExprKind::MethodCall(..) | ExprKind::Binary(..) => true,
102137

103-
// FIXME: this is probably wrong.
104138
// Inner blocks are rvalues.
105139
ExprKind::If(..) | ExprKind::Loop(..) | ExprKind::Match(..) | ExprKind::Block(..) => true,
106140

0 commit comments

Comments
 (0)