memory alignment issues with union

社会主义新天地 提交于 2019-12-23 14:20:44

问题


Is there guarantee, that memory for this object will be properly aligned if we create object of this type in stack?

union my_union
{
  int value;
  char bytes[4];
};

If we create char bytes[4] in stack and then try to cast it to integer there might be alignment problem. We can avoid that problem by creating it in heap, however, is there such guarantee for union objects? Logically there should be, but I would like to confirm.

Thanks.


回答1:


Well, that depends on what you mean.

If you mean:

Will both the int and char[4] members of the union be properly aligned so that I may use them independently of each other?

Then yes. If you mean:

Will the int and char[4] members be guaranteed to be aligned to take up the same amount of space, so that I may access individual bytes of the int through the char[4]?

Then no. This is because sizeof(int) is not guaranteed to be 4. If ints are 2 bytes, then who knows which two char elements will correspond to the int in your union (the standard doesn't specify)?

If you want to use a union to access the individual bytes of an int, use this:

union {
  int i;
  char c[sizeof(int)];
};

Since each member is the same size, they're guaranteed to occupy the same space. This is what I believe you want to know about, and I hope I've answered it.




回答2:


Yeah, unions would be utterly useless otherwise.



来源:https://stackoverflow.com/questions/4496423/memory-alignment-issues-with-union

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