Search code examples
rustalignmentmemory-layout

Is it possible to have a type with a larger alignment than its own size?


Is it ever possible to have a type in Rust with a larger alignment than its own size? Conversely, does the rust compiler always add padding to a type to make its size at least a multiple of its alignment?

This simple example code would seem to indicate that the answer is no, all types have a size that is a multiple of their alignment, but I wanted to make sure there aren't more esoteric possibilities.

use std::mem::{size_of, align_of};

struct b1 {
    byte: u8
}

#[repr(align(4))]
struct b4 {
    byte: u8
}

struct b5 {
    a: u8,
    b: u8,
    c: u8,
    d: u8,
    e: u8,
}

#[repr(align(8))]
struct b8 {
    a: u8,
    b: u8,
    c: u8,
    d: u8,
    e: u8,
}

fn main() {
    assert_eq!(size_of::<b1>(), 1);
    assert_eq!(align_of::<b1>(), 1);

    assert_eq!(size_of::<b4>(), 4);
    assert_eq!(align_of::<b4>(), 4);

    assert_eq!(size_of::<b5>(), 5);
    assert_eq!(align_of::<b5>(), 1);

    assert_eq!(size_of::<b8>(), 8);
    assert_eq!(align_of::<b8>(), 8);
}

There is a similar question for C++, where the answer seems to be "not in standard C++, but some compiler extensions support it. You can't create an array of T in that case".


Solution

  • The Rust reference has this to say about size and alignment (emphasis mine):

    Size and Alignment

    [...]

    The size of a value is the offset in bytes between successive elements in an array with that item type including alignment padding. The size of a value is always a multiple of its alignment. The size of a value can be checked with the size_of_val function.