GCC的strict aliasing机制

在编译一个项目的时候,发现有这样的warning信息:

dereferencing type-punned pointer will break strict-aliasing rules

google了一下,发现这是因为GCC3中引入了strict-aliasing机制导致的

gcc 3 manual 对于 -fstrict-aliasing 参数的说明是:Allows the compiler to assume the strictest aliasing rules applicable to the language being compiled.  For C (and C++), this activates optimizations based on the type of expressions.  In particular, an object of one type is assumed never to reside at the same address as an object of a different type, unless the types are almost the same.  For example, an "unsigned int" can alias an "int", but not a "void*" or a "double".  A character type may alias any other type.

strict-aliasing可以通过-fstrict-aliasing打开,同时,当采用了-O2等编译选项的时候也会默认打开。

解决的办法:

1.使用-fno-strict-aliasing编译选项,好处是避免了上述的危险,坏处则是无法享受到strict alias的性能优化

2.使用union,而不要简单的把一种类型的指针转换为另一个类型。

posted @ 2012-04-17 19:05  传灯  阅读(1266)  评论(0编辑  收藏  举报