结构填充和包装 [英] Structure padding and packing
问题描述
考虑:
struct mystruct_A
{
char a;
int b;
char c;
} x;
struct mystruct_B
{
int b;
char a;
} y;
结构体的大小分别为 12 和 8.
The sizes of the structures are 12 and 8 respectively.
这些结构是填充的还是压缩的?
Are these structures padded or packed?
什么时候进行填充或打包?
When does padding or packing take place?
推荐答案
Padding 将结构成员与自然"地址边界对齐 - 例如,int
成员将具有偏移量,在 32 位平台上为 mod(4) == 0
.默认情况下填充是打开的.它将以下间隙"插入到您的第一个结构中:
Padding aligns structure members to "natural" address boundaries - say, int
members would have offsets, which are mod(4) == 0
on 32-bit platform. Padding is on by default. It inserts the following "gaps" into your first structure:
struct mystruct_A {
char a;
char gap_0[3]; /* inserted by compiler: for alignment of b */
int b;
char c;
char gap_1[3]; /* -"-: for alignment of the whole struct in an array */
} x;
Packing,另一方面防止编译器进行填充 - 这必须明确要求 - 在 GCC 下它是 __attribute__((__packed__))
,所以以下内容:
Packing, on the other hand prevents compiler from doing padding - this has to be explicitly requested - under GCC it's __attribute__((__packed__))
, so the following:
struct __attribute__((__packed__)) mystruct_A {
char a;
int b;
char c;
};
将在 32 位架构上生成 6
大小的结构.
would produce structure of size 6
on a 32-bit architecture.
尽管如此 - 未对齐的内存访问在允许它的架构(如 x86 和 amd64)上速度较慢,并且在诸如 SPARC 的严格对齐架构上被明确禁止.
A note though - unaligned memory access is slower on architectures that allow it (like x86 and amd64), and is explicitly prohibited on strict alignment architectures like SPARC.
这篇关于结构填充和包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!