Skip to content

Better diagnostic for unaligned reference in println! #87946

@osa1

Description

@osa1

Tried with current master (ccffcaf).

This builds without warnings:

#[repr(packed)]
pub struct ObjInd {
    _header: u32,
    field: u32,
}

pub unsafe fn test(obj: *const ObjInd) {
    let field = (*obj).field;
    println!("{}", field);
}

But this generates a "ref to packed field" warning:

#[repr(packed)]
pub struct ObjInd {
    _header: u32,
    field: u32,
}

pub unsafe fn test(obj: *const ObjInd) {
    println!("{}", (*obj).field);
}

Output:

   Compiling packed_field_ptr v0.1.0 (/home/omer/rust/packed_field_ptr)
warning: reference to packed field is unaligned
 --> src/lib.rs:8:20
  |
8 |     println!("{}", (*obj).field);
  |                    ^^^^^^^^^^^^
  |
  = note: `#[warn(unaligned_references)]` on by default
  = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
  = note: for more information, see issue #82523 <https://github.com/rust-lang/rust/issues/82523>
  = note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced)

warning: `packed_field_ptr` (lib) generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.11s

Same with similar macros like writeln.

My guess is println is taking reference of its arguments, to avoid moving. No idea how to fix these warnings or if it's even possible without breaking backwards compat by making println move the args.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions