Does Aliasing/Alignment issues occur for an Array within a Structure?

守給你的承諾、 提交于 2019-12-11 14:09:28

问题


If we have an array within a struct:

struct Names
{
   uint8 fileId;
   uint8 name[50];
};

and then we try to assign a uint16 from the array to a uint16 variable like:

uint16 someName = *((uint16 *)&NamesObj.name[21]);

Will this violate aliasing rule/alignment rules and lead to undefined behaviour?


回答1:


Yes, this violates C rules. The objects in name are uint8 (presumably some unsigned 8-bit integer type), and they are accessed through a pointer to uint16 (presumably some 16-bit integer type).

The relevant part of the 2011 C standard, from draft N1570, is 6.5 7:

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:

— a type compatible with the effective type of the object,

— a qualified version of a type compatible with the effective type of the object,

— a type that is the signed or unsigned type corresponding to the effective type of the object,

— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,

— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or

— a character type.

The type uint16 is none of these.



来源:https://stackoverflow.com/questions/48799736/does-aliasing-alignment-issues-occur-for-an-array-within-a-structure

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