Skip to content

transmute documentation does not explicitly mention alignment requirement #82493

Closed
@Lonami

Description

@Lonami

The documentation for std::mem::transmute reads:

Both types must have the same size. Neither the original, nor the result, may be an invalid value.

However, it does not mention that they must also have the same alignment. You would only learn about this if you try to dig into the code examples further down the page:

...
// Therefore, the new inner type must have the
// exact same size, *and the same alignment*, as the old type.
// The same caveats exist for this method as transmute, for
...

Must the types T and U have the same alignment, or is that a particular quirk of the example?

In any case, I think the documentation should explicitly mention alignment, because the compiler succeeds to compile the following with no warnings (playground), and I believe this is undefined behaviour:

#[repr(align(2))]
struct Foo([u8; 8]);

#[repr(align(8))]
struct Bar([u8; 8]);

fn main()  {
    let _x: Bar = unsafe { std::mem::transmute(Foo([0; 8])) };
}

@rustbot modify labels: +T-doc +C-enhancement

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions