[英]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:我有一些定义结构的 c++ 代码:
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.我知道这个结构在分配时将始终在可被 2 整除的地址上对齐,因为必要时会在结构前面添加一个填充字节。
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];
现在,如果我将字节存储在数组
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?结构是否有 50/50 的机会错位? 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.我知道我可以将数组对齐在 2 字节边界上,以避免甚至不必考虑这一点。 Curiosity is my main reason for asking.
好奇是我问的主要原因。
Use memcpy
使用
memcpy
IcmpHdr header;
memcpy(&header, byte_array, sizeof(header));
If you use modern optimizing compiler it is very unlikely memcpy
to be called.如果您使用现代优化编译器,则不太可能调用
memcpy
。
https://godbolt.org/z/6P5M333dv https://godbolt.org/z/6P5M333dv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.