取消引用类型惩罚指针会破坏严格别名规则

时间:2018-06-02 17:16:58

标签: c pointers casting gcc-warning

编译过程中出现以下错误:

ccm.c:152:5: error: dereferencing type-punned pointer will break strict-aliasing rules [-Werror=strict-aliasing]
      HWREG(AES_AES_IV_0) = ((uint32_t *)&ui8A0)[0];

ccm.c:325:5: error: dereferencing type-punned pointer will break strict- aliasing rules [-Werror=strict-aliasing]
      ((uint32_t  *)&ui8MIC)[0] = HWREG(AES_AES_TAG_OUT_0);

第152-155行:

HWREG(AES_AES_IV_0) = ((uint32_t  *)&ui8A0)[0];
HWREG(AES_AES_IV_1) = ((uint32_t  *)&ui8A0)[1];
HWREG(AES_AES_IV_2) = ((uint32_t  *)&ui8A0)[2];
HWREG(AES_AES_IV_3) = ((uint32_t  *)&ui8A0)[3];

ui8A0是16个大小的 uint8_t 数组:

uint8_t  ui8A0[16];

第325-328行:

((uint32_t  *)&ui8MIC)[0] = HWREG(AES_AES_TAG_OUT_0);
((uint32_t  *)&ui8MIC)[1] = HWREG(AES_AES_TAG_OUT_1);
((uint32_t  *)&ui8MIC)[2] = HWREG(AES_AES_TAG_OUT_2);
((uint32_t  *)&ui8MIC)[3] = HWREG(AES_AES_TAG_OUT_3);

ui8MIC是16个大小的 uint8_t 数组:

uint8_t volatile ui8MIC[16];

HWREG宏看起来像这样:

#define HWREG(x)                                                              \
        (*((volatile uint32_t *)(x)))

这就是我理解的方式: ui8A0是一个数组,&ui8A0是第一个元素的地址,(uint32_t *)&ui8A0是数组的地址,其中元素是uint32_t,与之前的uint8_t相反,((uint32_t *)&ui8A0)[0]是值数组的第一个元素的元素是uint32_t。

所以基本上这段代码必须将ui8A0的4个元素传递给HWREG宏。

看起来像这个问题:https://stackoverflow.com/a/20956250/1625856 但我宁愿不使用基于联合的解决方案。

还有其他更简单的方法来处理吗?

我唯一的想法是替换:

HWREG(AES_AES_IV_1) = ((uint32_t  *)&ui8A0)[1];

使用:

HWREG(AES_AES_IV_1) = (uintptr_t)&ui8A0[4];

0 个答案:

没有答案