gcc, strict-aliasing, and casting through a union

后端 未结 7 564
时光说笑
时光说笑 2020-11-28 06:22

Do you have any horror stories to tell? The GCC Manual recently added a warning regarding -fstrict-aliasing and casting a pointer through a union:

[.

7条回答
  •  情歌与酒
    2020-11-28 07:04

    Aliasing occurs when the compiler has two different pointers to the same piece of memory. By typecasting a pointer, you're generating a new temporary pointer. If the optimizer reorders the assembly instructions for example, accessing the two pointers might give two totally different results - it might reorder a read before a write to the same address. This is why it is undefined behavior.

    You are unlikely to see the problem in very simple test code, but it will appear when there's a lot going on.

    I think the warning is to make clear that unions are not a special case, even though you might expect them to be.

    See this Wikipedia article for more information about aliasing: http://en.wikipedia.org/wiki/Aliasing_(computing)#Conflicts_with_optimization

提交回复
热议问题