Skip to content

When using std::ptr::copy and similar methods, does the memory need to be valid for T? #330

Description

Plenty of methods in std::ptr take a generic T and use *mut/const T, but does this mean that the following code is UB?

let src: u8 = 42;
let mut dest: u8 = 10;
std::ptr::copy(&src as *const u8 as *const bool, &mut dest as *mut u8 as *mut bool);

What about copying a u32 as a (u16, u8), or a (u16, u8, !), that doesn't uninit any padding, right?

Same question applies to copy_nonoverlapping, swap(_nonoverlapping), write_bytes. I don't see any other methods that this would apply to.

What about copying a pointer with an integer type, that preserves provenance?


I'd be inclined to say "no, it's not UB, the generic parameter is only used for its size and alignment, no other property of the type matters", but if that's the case, we should make that clear. It definitely seems to be implied.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions