Skip to content

UB in example code for E0617 #86908

Closed
@booleancoercion

Description

@booleancoercion

I was browsing through some errors and I noticed the explanation for E0617:

Attempted to pass an invalid type of variable into a variadic function.

Erroneous code example:

'''
extern "C" {
    fn printf(c: *const i8, ...);
}

unsafe {
    printf(::std::ptr::null(), 0f32);
    // error: cannot pass an `f32` to variadic function, cast to `c_double`
}
'''

Certain Rust types must be cast before passing them to a variadic function,
because of arcane ABI rules dictated by the C standard. To fix the error,
cast the value to the type specified by the error message (which you may need
to import from `std::os::raw`).

In this case, `c_double` has the same size as `f64` so we can use it directly:

'''
unsafe {
    printf(::std::ptr::null(), 0f64); // ok!
}
'''

(replaced backticks with quotes to fix the formatting issues)

The diagnostic itself is fine and correctly suggests how to fix the error, however I think the code in question is troublesome - passing a null pointer to printf is undefined behavior! As a language that prides itself in avoiding UB, I find it odd that the documentation would make a mistake like that. I think that the nullptr could also be a distraction to the reader.

On further discussion, someone also pointed out that the presented signature of printf is wrong, because it should have an integer return type.

Perhaps these issues could be fixed by replacing printf with a dummy function foo that takes variadic arguments only? In my opinion, it would make a cleaner explanation overall.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler 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