diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 2330978e67f1..627aad27d7fa 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -2165,6 +2165,13 @@ fn lint_cstring_as_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, source: &hir: if cx.tcx.is_diagnostic_item(sym!(result_type), def.did); if match_type(cx, substs.type_at(0), &paths::CSTRING); then { + // Ignore, if ptr is used in a call in the same expression #5838 + if let Some((_, hir::Node::Expr(parent_expr))) = cx.tcx.hir().parent_iter(expr.hir_id).next() { + if let hir::ExprKind::Call(_, _) = parent_expr.kind { + return; + } + } + span_lint_and_then( cx, TEMPORARY_CSTRING_AS_PTR, diff --git a/tests/ui/cstring.rs b/tests/ui/cstring.rs index 6cdd6b4ff6e7..f7cf88dcf8c7 100644 --- a/tests/ui/cstring.rs +++ b/tests/ui/cstring.rs @@ -17,8 +17,13 @@ mod issue4375 { fn foo(data: *const c_char); } - pub fn bar(v: &[u8]) { + pub fn bar_ok(v: &[u8]) { let cstr = CString::new(v); unsafe { foo(cstr.unwrap().as_ptr()) } } + + pub fn bar_bad(v: &[u8]) { + let c_str = CString::new(v).unwrap().as_ptr(); + unsafe { foo(c_str) } + } } diff --git a/tests/ui/cstring.stderr b/tests/ui/cstring.stderr index 87cb29be5775..cf01af395b9c 100644 --- a/tests/ui/cstring.stderr +++ b/tests/ui/cstring.stderr @@ -30,17 +30,17 @@ LL | CString::new("foo").expect("dummy").as_ptr(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: you are getting the inner pointer of a temporary `CString` - --> $DIR/cstring.rs:22:22 + --> $DIR/cstring.rs:26:21 | -LL | unsafe { foo(cstr.unwrap().as_ptr()) } - | ^^^^^^^^^^^^^^^^^^^^^^ +LL | let c_str = CString::new(v).unwrap().as_ptr(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: that pointer will be invalid outside this expression help: assign the `CString` to a variable to extend its lifetime - --> $DIR/cstring.rs:22:22 + --> $DIR/cstring.rs:26:21 | -LL | unsafe { foo(cstr.unwrap().as_ptr()) } - | ^^^^^^^^^^^^^ +LL | let c_str = CString::new(v).unwrap().as_ptr(); + | ^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 3 previous errors