在gcc 4.6.1 bug上严格的别名警告

use*_*635 6 c++ gcc strict-aliasing

我正在尝试使用gcc编译以下内容 -pedantic-errors -pedantic -Wall -O2

#include <iostream>

void reset_uint32(uint32_t* pi)
{
    char* c = (char*)(pi);
    uint16_t* j = (uint16_t*)(c); // warning?
    j[0] = 0;
    j[1] = 0;
}

void foo()
{
    uint32_t i = 1234;
    reset_uint32(&i);
}

int main() {
   foo();
}
Run Code Online (Sandbox Code Playgroud)

但我没有看到任何严格的别名警告.我也尝试过启用

-fstrict-aliasing
-Wstrict-aliasing
Run Code Online (Sandbox Code Playgroud)

但仍然没有警告.这是一个错误吗?

fsc*_*enm 1

我重写了您的示例以生成有关违反严格别名规则的警告:

void foo(int* pi) {
    short* j = (short*)pi;
    j[0] = j[1] = 0;
}

int main() {
    int i = 1234;

    foo(&i);

    short* j = (short*)&i;
    j[0] = j[1] = 0;
}
Run Code Online (Sandbox Code Playgroud)

-Wstrict-aliasing=2尽管如此,如果您使用而不是编译代码,g++ 4.6 只会显示警告-Wstrict-aliasing。此外,它仅显示 中的强制转换警告 main(),而不是 中的强制转换警告foo()。但我不明白编译器如何/为什么会以不同的方式看待这两个转换。