I have some c code that defines a struct:
struct IcmpHdr
{
uint8_t m_type;
uint8_t m_code;
uint16_t m_chksum;
uint16_t m_id;
uint16_t m_seq;
} __attribute__((packed, aligned(2)))
I understand that this struct will always be aligned on an address divisible by 2 when allocated because a padding byte ahead of the struct will be added if necessary.
This struct gets cast to a byte array before going over the wire to be unpacked on the the receiving end. Now what happens on the receiving end if I store the bytes in an array char byte_array[8];
And then ultimately cast this as a pointer to my type?
IcmpHdr* header = (IcmpHdr*)byte_array;
Will the struct have a 50/50 chance of being misaligned? Could this cause undefined behavior when dereferencing the members? Other issues?
I know I could just align the array on a 2 byte boundary to avoid even having to think about this. Curiosity is my main reason for asking.
CodePudding user response:
- Avoid pointer punning as it almost always breaks strict aliasing rules.
- Alignment of your structure does not matter as your byte array does not have to be 2 bytes aligned.
Use memcpy
IcmpHdr header;
memcpy(&header, byte_array, sizeof(header));
If you use modern optimizing compiler it is very unlikely memcpy
to be called.