C中的结构填充 [英] Structure Padding in C

查看:38
本文介绍了C中的结构填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 C 中有以下结构定义

If I have a structure definition in C of the following

typedef struct example 
{
  char c;
  int ii;
  int iii;
};

当我声明上述结构类型的变量时分配的内存应该是多少.例子ee;

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?

推荐答案

尝试一下.在不同的系统上可能会有所不同.

Try it. It may be different on different systems.

#include <stdio.h>
#include <stddef.h> /* for offsetof */
struct example { char c; int ii; int iii; };
int main(int argc, char *argv[])
{
    printf("offsetof(struct example, c) == %zd\n", offsetof(struct example, c));
    printf("offsetof(struct example, ii) == %zd\n", offsetof(struct example, ii));
    printf("offsetof(struct example, iii) == %zd\n", offsetof(struct example, iii));
    return 0;
}

输出:

offsetof(struct example, c) == 0
offsetof(struct example, ii) == 4
offsetof(struct example, iii) == 8

注意sizeof(char) == 1,但ii字段前有四个字节.额外的三个字节是填充.填充的存在是为了确保数据类型在处理器的正确边界上排列.

Note that sizeof(char) == 1, but there are four bytes before the ii 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:

  • 访问速度较慢(大多数 x86)
  • 访问必须由内核处理并且速度非常慢(各种 PowerPC)(这导致一些计算机游戏在快速 PPC 603 处理器上运行非常缓慢,而在较慢的 PPC 601 处理器上运行得很好.)
  • 程序崩溃(各种 SPARC)

我知道填充没有已知的风险.真正发生的唯一问题是,使用不同编译器(已知 GCC 与 MSVC 会导致此问题)编译的两个程序使用不同的填充并且无法共享结构.如果来自不同编译器的代码链接在一起,这也会导致崩溃.由于填充通常由平台 ABI 指定,因此这种情况很少见.

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.

这篇关于C中的结构填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆