小编Lig*_*Bit的帖子

严格的别名规则,误报还是漏报?

我在 C 中遇到严格别名问题。我使用的是 GCC 4.7.1。

示例 1:
当使用 -fstrict-aliasing -Wstrict-aliasing=3 编译此代码时,我收到“警告:取消引用类型双关指针将破坏严格别名规则”

#include <stdio.h>
#include <stdint.h>

int main(void)
{
    uint8_t a[4] = {0x01, 0x23, 0x45, 0x67};
    uint32_t b;

    b = *(uint32_t *)a;

    printf("%x\n", b);

    return(0);
}
Run Code Online (Sandbox Code Playgroud)


示例 2:
此代码使用 -fstrict-aliasing 和 -Wstrict-aliasing=3 或 -Wstrict-aliasing=2 或 -Wstrict-aliasing=1 时不发出警告

#include <stdio.h>
#include <stdint.h>

int main(void)
{
    uint8_t a[4] = {0x01, 0x23, 0x45, 0x67};
    uint32_t b;
    void *p;

    p = a;
    b = *(uint32_t *)p;

    printf("%x\n", b);

    return(0);
}
Run Code Online (Sandbox Code Playgroud)


两个例子都工作正常。

使用 union 也是未定义的行为,并且在我的情况下使用 memcpy() …

c strict-aliasing gcc-warning

2
推荐指数
1
解决办法
534
查看次数

标签 统计

c ×1

gcc-warning ×1

strict-aliasing ×1