简体   繁体   中英

What will happen if I cast a byte array to an __attribute__((packed, aligned(2))) 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.

  1. Avoid pointer punning as it almost always breaks strict aliasing rules.
  2. 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.

https://godbolt.org/z/6P5M333dv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM