内存对齐问题与联合 [英] memory alignment issues with union
问题描述
有保证,如果我们在堆栈中创建这个类型的对象,这个对象的内存是否会正确对齐?
union my_union
{
int value;
char bytes [4];
};
如果我们在堆栈中创建char字节[4],然后尝试将其转换为整数,对齐问题。我们可以通过在堆中创建它来避免这个问题,但是,有没有这样的保证联合对象?逻辑上应该有,但我想确认。
感谢。
如果您的意思是:
int
和char [4]
成员可以正确对齐,以便我们可以彼此独立地使用它们?
然后是。如果您的意思是:
int
和[4]
成员保证对齐占用相同的空间,以便我可以访问int
的各个字节char [4]
?
这是因为 sizeof(int)
不能保证是4.如果 int
s是2字节,其中两个 char
元素将对应于 union
int >
int $ c的各个字节$ c>,请使用: union {
int i;
char c [sizeof(int)];
};
由于每个成员的大小相同,所以它们保证占用相同的空间。这是我想你想知道的,我希望我已经回答了。
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.
解决方案 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 int
s 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.
这篇关于内存对齐问题与联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!