Skip to content

Commit

Permalink
ignore usage in same expr temporary_cstring_as_ptr
Browse files Browse the repository at this point in the history
  • Loading branch information
wiomoc committed Aug 16, 2020
1 parent 3bd9889 commit dc74fd0
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
7 changes: 7 additions & 0 deletions clippy_lints/src/methods/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 6 additions & 1 deletion tests/ui/cstring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
}
}
12 changes: 6 additions & 6 deletions tests/ui/cstring.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit dc74fd0

Please sign in to comment.