Skip to content

Missing build warning "temporary_string_as_ptr" when String is used with "as_ptr" on one line #90449

Closed as duplicate of#139249
@mirao

Description

@mirao

Playground

It's rather a suggestion than a bug.

Have this code:

use std::ffi::CString;

fn main() {
    let pointer = CString::new("Hello world!").unwrap().as_ptr();
    unsafe {
        println!("{:?}", *pointer as u8 as char);
    }
}

Rust reports the warning rustc(temporary_cstring_as_ptr) during build. The detail is this `CString` is deallocated at the end of the statement, bind it to a variable to extend its lifetime which is expected 🆗 .
If you run the code, a "random" character will be printed and that's of course unexpected. A solution is an assignment of the string into a standalone variable as explained here.


Have the same code, but this time it uses String instead of CString:

fn main() {
    let pointer = String::from("Hello world!").as_ptr();

    unsafe {
        println!("{:?}", *pointer as char);
    }
}

I expected to see this happen:

  • I should get similar kind of warning as in case of CString, because also in this case the pointer is dangling and if you run the code, a random character will be printed. A solution is the same as for CString

Instead, this happened:

  • Rust doesn't warn

Meta

rustc --version --verbose:

rustc 1.58.0-nightly (e249ce6b2 2021-10-30)
binary: rustc
commit-hash: e249ce6b2345587d6e11052779c86adbad626dff
commit-date: 2021-10-30
host: x86_64-unknown-linux-gnu
release: 1.58.0-nightly
LLVM version: 13.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions