Skip to content

Can't define unsafe extern "C" fn #10025

Closed
@kmcallister

Description

@kmcallister

Both

unsafe extern "C" fn foobar() {
    *(0 as *mut u8) = 0;
}

and

extern "C" unsafe fn foobar() {
    *(0 as *mut u8) = 0;
}

give me a syntax error. But it's not the case that an extern "C" function is automatically unsafe. Dropping the unsafe keyword gives me

error: dereference of unsafe pointer requires unsafe function or block

And this code compiles and segfaults:

extern "C" fn foobar() {
    unsafe {
        *(0 as *mut u8) = 0;
    }
}

#[fixed_stack_segment]
fn main() {
    foobar()
}

So I can't declare an extern "C" function (for external linkage, with #[no_mangle]) without also allowing safe Rust code to call that function, breaking memory safety.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions