What will happen if I cast a byte array to an __attribute__((packed, aligned(2))) struct?

  arrays, c++, memory-alignment, struct

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.

Source: Windows Questions C++

LEAVE A COMMENT