Skip to main content
2 of 2
added 23 characters in body
Lundin
  • 22.3k
  • 1
  • 30
  • 83

You cannot do dirty casts like this in C. There are multiple problems:

  • The data you copy from might not be aligned.
  • The struct might have padding bytes to compensate for internal alignment that are not present in the data you copy from.
  • Dereferencing this struct pointer after the cast leads to a strict pointer aliasing violation, meaning it's undefined behavior bug which could result in incorrect machine code getting generated.

The safest and most portabile solution is write a function that does serialization/deserialization of the struct data. That is, a function writing to each member manually. This is slightly slower due to the overhead code but the most portable.

Less portable but probably faster is to memcpy the data. If you do this, you must be absolutely sure that the struct has no padding. Which you aren't, the struct you posted is very poorly designed by someone who has never heard of alignment, since it has padding gaps all over it. If you re-design the struct to ensure there's no padding, you could use memcpy or similar methods.

(Union type punning is yet another option.)

Lundin
  • 22.3k
  • 1
  • 30
  • 83