Skip to content

align_of for small structs does not give the actual alignment of pointers #21611

Closed
@huonw

Description

@huonw
#[derive(Debug, Copy)]
struct Foo {
    x: u8,
}

fn main() {
    let f = Foo { x: 1 };
    let vec = vec![f, f, f, f, f];

    println!("size: {}", std::mem::size_of::<Foo>());
    println!("align: {}", std::mem::align_of::<Foo>());
    println!("alignment offset: {}", (&vec[2] as *const _ as usize) % std::mem::align_of::<Foo>());
}

It prints size: 1 align: 8 alignment offset: 2. I would expect that every value of type T is aligned to align_of::<T>() (i.e. the % should always give 0).

On x86-64, this applies to anything with alignment < 8, including #[repr(packed)] structs.

I'm not sure it's a bug, but it does seem rather confusing.

Also, NB. this means size_of < align_of.

(min_align_of acts more like I might expect.)

Metadata

Metadata

Assignees

Labels

E-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.P-mediumMedium priority

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions