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.
IcmpHdrobject and read the data into it (pass it as the buffer to the network call that writes the received data into a buffer). In cases where you are reading a packet and do not know which type it is until after starting to inspect it, you can use a union of the various packet types. Another option is to read into a character buffer and thenmemcpyinto a properIcmpHdrobject.IcmpHdr, accessing an array ofcharusing an lvalue of typeIcmpHdrcan result in the compiler generating code that does not do what you want.