如果我在以下C中有结构定义
typedef struct example
{
char c;
int ii;
int iii;
};
Run Code Online (Sandbox Code Playgroud)
当我声明上述结构类型的变量时,应分配的内存是多少.例如ee;
什么是结构填充以及是否存在与结构填充相关的风险?
Die*_*Epp 10
试试吧.它可能在不同的系统上有所不同.
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
offsetof(struct example, c) == 0
offsetof(struct example, ii) == 4
offsetof(struct example, iii) == 8
Run Code Online (Sandbox Code Playgroud)
请注意sizeof(char) == 1
,但ii
字段前有四个字节.额外的三个字节是填充.存在填充以确保数据类型排列在处理器的正确边界上.
如果处理器进行未对齐访问,则可能发生以下各种情况:
我知道填充没有已知的风险.真正发生的唯一问题是用不同编译器编译的两个程序(已知GCC与MSVC导致这种情况)使用不同的填充并且不能共享结构.如果来自不同编译器的代码链接在一起,这也可能导致崩溃.由于填充通常由平台ABI指定,因此这种情况很少见.