加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么没有为此代码生成严格别名警告?

发布时间:2020-12-16 06:54:55 所属栏目:百科 来源:网络整理
导读:我有以下代码: 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"); }} 我正在使用以
我有以下代码:

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");
    }
}

我正在使用以下命令行编译代码:

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

我正在使用GCC 4.5.0.我希望编译器打印出警告:

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

但它永远不会.我可以在其他情况下打印警告,但我想知道为什么,在这种情况下,它不是.这不是打破严格别名规则的明显例子吗?

解决方法

GCC的-Wstrict-aliasing = 2的文档说(强调我的):

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.

看起来你的代码不是太棘手,所以我不确定为什么会出现假阴性,但也许是因为你没有使用&执行别名的运算符地址(可能是“仅在收到地址时发出警告”的含义)

更新:

它来自不使用address-of运算符.如果我将以下代码添加到foo.c文件中:

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

    foo( &myB);

    return 0;
}

发出警告.

如果usefoo()位于单独的编译单元中,则不会发出警告.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读