gpt4 book ai didi

c - 解决 GCC 警告 : "dereferencing type-punned pointer will break strict-aliasing rules" by temporary pointer

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:49 24 4
gpt4 key购买 nike

在函数中

size_t csps_socket_read(csps_socket_t *s, csps_packet_wrapper_t *packet, size_t sz)

我收到警告:“解引用类型双关指针将破坏严格别名规则 [-Wstrict-aliasing]”在以下行中:

packet_size = ((csps_packet_full_header_t *)s->receive_mem)->size + header_size;

如果我这样重写:

csps_packet_full_header_t *packet_full_header = (csps_packet_full_header_t *)s->receive_mem;
packet_size = packet_full_header->size + header_size;

我没有收到任何警告。为什么?问题仍然存在但 gcc 看不到吗?

这里是涉及的结构:

typedef struct csps_socket_t_
{
void* fp;
bool open;
uint8_t receive_mem[CSPS_SOCKET_MEM];
uint32_t receive_index;
} csps_socket_t;

typedef struct ATTR_PACKED csps_packet_full_header_t_
{
uint8_t version:4;
uint8_t pclass:4;
uint8_t ch:1;
uint8_t reserved:7;
uint16_t size;
uint16_t sequence;
uint16_t checksum;
uint8_t src[8];
uint8_t dst[8];
} csps_packet_full_header_t;

最佳答案

基本上这是 GCC 的 -Wstrict-aliasing 机制中的错误。众所周知,它既会产生错误警告又会错过真正的混叠违规(请参阅开发人员的 this comment)。

问题在这两种情况下都存在,转换不相关的结构将违反别名规则并可能导致 GCC 产生意外代码。

关于c - 解决 GCC 警告 : "dereferencing type-punned pointer will break strict-aliasing rules" by temporary pointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43604699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com