MIDIPacketNext UB: Accessing Fields of Unaligned Struct
Closed this issue · 1 comments
The Problem
As listed in the RFC for raw references it is:
...essentially impossible to create a raw pointer pointing to an unaligned struct field: &packed.field as *const _ creates an intermediate unaligned reference, triggering undefined behavior because it is not aligned.
Assuming that MIDIPacket
s could be unaligned as discussed in #10, then our accessing the .length field
triggers this UB.
Potential Fixes
The most direct route would be to copy the MIDIPacket
(or part of it) to the stack, where reading its fields is not UB (see the very bottom of this section). I don't know if this is feasible because of the flexible-array-member .data
field.
So it seems to me that this likely depends on #10 being fixed first. We need some way to refer to MIDIPacket
before we can access its fields.
If we can get a raw pointer to the .length
field, it seems like we might be able to read it using std::ptr::read_unaligned()
.