Strict-aliasing and pointer to union fields

旧城冷巷雨未停 提交于 2019-12-05 11:56:02

The C standard says that aliasing via unions is explicitly permitted.

However check the following code:

void func(int *a, short *b)
{
     *a = 1; 
     printf("%f\n", *b);
}

The intent of the strict aliasing rule is that a and b should be assumed to not alias. However you could call func(&u.f1, &u.f2); .

To resolve this dilemma, a common sense solution is to say that the 'bypass permit' that unions have to avoid the strict aliasing rule only applies to when the union members are accessed by name.

The Standard doesn't explicitly state this. It could be argued that "If the member used..." (6.5.2.3) actually is specifying that the 'bypass' only occurs when accessing the member by name, but it's not 100% clear.

However it is hard to come up with any alternative and self-consistent interpretation. One possible alternative interpretation goes along the lines that writing func(&u.f1, &u.f2) causes UB because overlapping objects were passed to a function that 'knows' it does not receive overlapping objects -- sort of like a restrict violation.

If we apply this first interpretation to your example, we would say that the *a in your printf causes UB because the current object stored at that location is a short, and 6.5.2.3 doesn't kick in because we are not using the union member by name.

I'd guess based on your posted results that gcc is using the same interpretation.

This has been discussed before here but I can't find the thread right now.

The C99 Technical Corrigendum 3 is clarifying about the type-punning based on the union method by stating in the section 6.5.2.3:

If the member used to access the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called "type punning").

See here from 1042 through 1044

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!