开发者

memory alignment issues with union

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开发者_C百科 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.


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.


Yeah, unions would be utterly useless otherwise.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜