Rust C Structure alignment mismatch?

5134945
Opened by Don Park at 2015-12-31 19:58:56

I'm trying to craft a binding from rust into mruby (sebastianedwards/rust-mruby is obsolete). In debugging a segfault in a foreign function, I get conflicting answers as to the alignment of a rust struct.

#[repr(C)]
struct MRubyValue {
  value: [u8, ..8],
  tt: MRubyType,
}

Printing the size and align gives

    println!("MRubyValue size {} align {}", std::mem::size_of::<MRubyValue>(),
                                            std::mem::align_of::<MRubyValue>());
=>
MRubyValue size 12 align 8

I found some code on the internet which supposedly prints the same information, but the alignment is different.

    let tyd =
        unsafe {
            (*std::intrinsics::get_tydesc::<T>())
        };
    println!("name: {} size: {} align: {}", tyd.name, tyd.size, tyd.align);
=>
name: MRubyValue size: 12 align: 4

Is this a rust problem or a misunderstanding of the output? Thanks.

  1. A non-doc comment for align_of suggests that

    pub fn align_of<T>() -> uint {
        // We use the preferred alignment as the default alignment for a type. This
        // appears to be what clang migrated towards as well:
        //
        // http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20110725/044411.html
        unsafe { intrinsics::pref_align_of::<T>() }
    }
    

    I guess tydescs return the actual alignment. It's sort of weird to have a size that isn't a multiple of the alignment, isn't it? The second element in a [MRubyValue] wouldn't be aligned if align_of was right!

    Benjamin Herr at 2014-11-23 23:27:29

  2. tydesc was removed in https://github.com/rust-lang/rust/pull/23376, so this is moot now.

    Steve Klabnik at 2015-12-31 19:58:56