Skip to content

c2rust introduces UB in &a[i] by adding a * deref and & ref when there should only be an .offset #303

@jrmuizel

Description

@jrmuizel

Another issue I found when running miri on the generated code.

#include <stdlib.h>
struct Foo {
    int *data_ptr;
    int data[];
};

void f() {
    struct Foo *foo = malloc(sizeof(struct Foo));
    foo->data_ptr = &foo->data[0];
}

int main() {
    f();
}

translates to

extern "C" {
    #[no_mangle]
    fn malloc(_: libc::c_ulong) -> *mut libc::c_void;
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Foo {
    pub data_ptr: *mut libc::c_int,
    pub data: [libc::c_int; 0],
}
#[no_mangle]
pub unsafe extern "C" fn f() {
    let mut foo: *mut Foo =
        malloc(::std::mem::size_of::<Foo>() as libc::c_ulong) as *mut Foo;
    (*foo).data_ptr =
        &mut *(*foo).data.as_mut_ptr().offset(0 as libc::c_int as isize) as
            *mut libc::c_int;
}
unsafe fn main_0() -> libc::c_int { f(); return 0; }
#[main]
pub fn main() { unsafe { ::std::process::exit(main_0() as i32) } }
error: Undefined Behavior: memory access failed: pointer must be in-bounds at offset 12, but is outside bounds of alloc2017 which has size 8
  --> src/main.rs:20:9
   |
20 |         &mut *(*foo).data.as_mut_ptr().offset(0 as libc::c_int as isize) as
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ memory access failed: pointer must be in-bounds at offset 12, but is outside bounds of alloc2017 which has size 8
   |
   = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
   = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
           

The &mut *() dereferences the data member which allowed in C but not in Rust. Removing/folding the &mut * fixes the problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions