为什么这个code产生没有严格走样警告? [英] Why are no strict-aliasing warnings generated for this code?

查看:143
本文介绍了为什么这个code产生没有严格走样警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

struct A
{
    short b;
};

struct B
{
    double a;
};


void foo (struct B* src)
{
    struct B* b = src;
    struct A* a = (struct A*)src;

    b->a = sin(rand());

    if(a->b == rand())
    {
        printf("Where are you strict aliasing warnings?\n");
    }
}

我编译code使用以下命令行:

I'm compiling the code with the following command line:

gcc -c -std=c99 -Wstrict-aliasing=2 -Wall -fstrict-aliasing -O3 foo.c

我使用GCC 4.5.0。我预计编译器打印出警告:

I'm using GCC 4.5.0. I expected the compiler to print out the warning:

 warning: dereferencing type-punned pointer will break strict-aliasing rules

但它永远不会是。我能到打印出来的其他情况下的警告,但我不知道为什么,在这种情况下,事实并非如此。这难道不是打破严格走样规则的一个明显的例子?

But it never is. I can get the warning to be printed out for other cases, but I'm wondering why, in this case, it isn't. Is this not an obvious example of breaking the strict aliasing rules?

推荐答案

GCC的文档为 -Wstrict走样= 2 说(重点煤矿):

GCC's docs for -Wstrict-aliasing=2 says (emphasis mine):

2级:积极,快速,不要太
  precise。可还是有很多假的
  正片(不多达1级
  虽然),和几个假阴性(但
  可能不止1级)
。不比
  1级,它只是警告当一个地址
  取。警告关于不完整
  类型。在前台只运行。

Level 2: Aggressive, quick, not too precise. May still have many false positives (not as many as level 1 though), and few false negatives (but possibly more than level 1). Unlike level 1, it only warns when an address is taken. Warns about incomplete types. Runs in the frontend only.

这似乎是你的code是不是太棘手,所以我不知道为什么会是一个假阴性,但也许那是因为你不使用&安培; 地址运算符来执行走样(也可能什么是只警告当一个地址被占用的意思)

It seems like your code isn't too tricky, so I'm not sure why there'd be a false negative, but maybe it's because you don't use the & address-of operator to perform the aliasing (that might be what's meant by "only warns when an address is taken")

更新:

这是不使用地址的运营商。如果我下面的code添加到foo.c文件:

It is from not using the address-of operator. If I add the following code to the foo.c file:

int usefoo(void)
{
    struct B myB = {0};

    foo( &myB);

    return 0;
}

发出警告。

如果 usefoo()是在一个单独的编译单元,不发出警告。

If usefoo() is in a separate compilation unit, no warning is issued.

这篇关于为什么这个code产生没有严格走样警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆