C 中的结构填充
如果我在 C 中有一个结构定义,
typedef struct example
{
char c;
int ii;
int iii;
};
当我声明上述结构类型的变量时,应该分配什么内存。 例如 ee;
以及什么是结构填充以及结构填充是否存在任何风险?
If I have a structure definition in C of the following
typedef struct example
{
char c;
int ii;
int iii;
};
What should be the memory allocated when I declare a variable of the above structure type.
example ee;
and also what is structure padding and if there is any risk associated with structure padding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一下。在不同的系统上可能会有所不同。
输出:
请注意,
sizeof(char) == 1
,但在ii
字段之前有四个字节。额外的三个字节是填充。填充的存在是为了确保数据类型在处理器的正确边界上排列。如果处理器进行未对齐的访问,可能会发生各种情况:
我知道填充没有已知的风险。真正发生的唯一问题是使用不同编译器编译的两个程序(已知 GCC 与 MSVC 会导致此问题)使用不同的填充并且无法共享结构。如果来自不同编译器的代码链接在一起,这也可能导致崩溃。由于填充通常由平台 ABI 指定,因此这种情况很少见。
Try it. It may be different on different systems.
Output:
Note that
sizeof(char) == 1
, but there are four bytes before theii
field. The extra three bytes are padding. Padding exists to make sure that data types are lined up on the correct boundaries for your processor.If a processor makes an unaligned access, various things can happen:
I know of no known risks with padding. The only problem that really happens is that two programs compiled with different compilers (GCC vs MSVC has been known to cause this) use different padding and cannot share structures. This can also cause crashes if code from different compilers is linked together. Since padding is often specified by the platform ABI, this is rare.
在正常的 32 位下,它应该占用 12 个字节 -
c
字段将被填充。然而,这取决于体系结构和编译器。您始终可以使用编译器的 pragma 来声明结构的对齐方式(对于某些编译器,可以更改默认对齐方式)。
Under normal 32 bit it should take 12 bytes - the
c
field will be padded. This is architecture and compiler depended, however.You can always use a
pragma
for the compiler to declare the alignment for the structure (and for some compilers, change the default alignment).