为什么union和inner struct要加padding?
Why does union & inner struct add padding?
在 amd64 上,以下结构的大小为 16 字节:
typedef struct _my_struct {
void *a;
UINT32 b;
UINT16 c;
UINT8 d;
UINT8 e;
} my_struct;
但是当我将前三个变量放在一个联合中时,大小变为 24。为什么?
typedef struct _my_struct {
union {
struct {
void *a;
UINT32 b;
UINT16 c;
} my_inner;
struct {
void **f;
} my_inner2;
}
UINT8 d;
UINT8 e;
} my_struct;
您正在创建一个新的结构类型 (my_inner
)。编译器向该结构添加填充,使其大小变为 16 字节(对于 amd64)。然后它将填充添加到外部结构类型 (my_struct
),这使其大小增长到 24 字节。
仅供参考,不增加整体大小的最简单解决方案是执行以下操作:
typedef struct _my_struct {
union {
struct {
void *a;
UINT32 b;
UINT16 c;
} my_inner;
struct {
void **f;
} my_inner2;
struct {
UCHAR __PADDING[sizeof(void*) + sizeof(UINT32) + sizeof(UINT16)];
UINT8 d;
UINT8 e;
};
}
} my_struct;
它不漂亮,但它实现了我想要的,无需打包任何东西。
在 amd64 上,以下结构的大小为 16 字节:
typedef struct _my_struct {
void *a;
UINT32 b;
UINT16 c;
UINT8 d;
UINT8 e;
} my_struct;
但是当我将前三个变量放在一个联合中时,大小变为 24。为什么?
typedef struct _my_struct {
union {
struct {
void *a;
UINT32 b;
UINT16 c;
} my_inner;
struct {
void **f;
} my_inner2;
}
UINT8 d;
UINT8 e;
} my_struct;
您正在创建一个新的结构类型 (my_inner
)。编译器向该结构添加填充,使其大小变为 16 字节(对于 amd64)。然后它将填充添加到外部结构类型 (my_struct
),这使其大小增长到 24 字节。
仅供参考,不增加整体大小的最简单解决方案是执行以下操作:
typedef struct _my_struct {
union {
struct {
void *a;
UINT32 b;
UINT16 c;
} my_inner;
struct {
void **f;
} my_inner2;
struct {
UCHAR __PADDING[sizeof(void*) + sizeof(UINT32) + sizeof(UINT16)];
UINT8 d;
UINT8 e;
};
}
} my_struct;
它不漂亮,但它实现了我想要的,无需打包任何东西。