Skip to content

Instantly share code, notes, and snippets.

@BruceChen7
Last active April 26, 2022 14:02
Show Gist options
  • Save BruceChen7/c65e2f748fb2fd0f82b8ee2a6619a6a9 to your computer and use it in GitHub Desktop.
Save BruceChen7/c65e2f748fb2fd0f82b8ee2a6619a6a9 to your computer and use it in GitHub Desktop.
#c#memory
// 在64机器上,返回16字节
// 存在 pading
// http://www.catb.org/esr/structure-packing/
struct foo3 {
char *p; /* 8 bytes */
char c; /* 1 byte */
};
struct foo3 singleton;
struct foo3 quad[4];
// 等价于
struct foo3 {
char *p; /* 8 bytes */
char c; /* 1 byte */
char pad[7];
};
// 如果你的结构有结构成员,内部结构也希望有最长标量的对齐方式。
struct foo5 {
char c;
struct foo5_inner {
char *p;
short x;
} inner;
};
// 等价于
struct foo5 {
char c; /* 1 byte*/
char pad1[7]; /* 7 bytes */
struct foo5_inner {
char *p; /* 8 bytes */
short x; /* 2 bytes */
char pad2[6]; /* 6 bytes */
} inner;
};
// Bitfields
struct foo6 {
short s;
char c;
int flip:1;
int nybble:4;
int septet:7;
};
// 等价于, c99
struct foo6 {
short s; /* 2 bytes */
char c; /* 1 byte */
int flip:1; /* total 1 bit */
int nybble:4; /* total 5 bits */
int pad1:3; /* pad to an 8-bit boundary */
int septet:7; /* 7 bits */
int pad2:25; /* pad to 32 bits */
};
// 也可能是下面的模式,有可能是填充在有效负载之前
// C99 rules 没有保证padding的都是0,可能是垃圾值
// 位域不能跨越机器字边界的限制意味着,虽然以下结构的前两个结构如你所期望的那样被装入一个和两个32位字
struct foo6 {
short s; /* 2 bytes */
char c; /* 1 byte */
int pad1:3; /* pad to an 8-bit boundary */
int flip:1; /* total 1 bit */
int nybble:4; /* total 5 bits */
int pad2:25; /* pad to 32 bits */
int septet:7; /* 7 bits */
};
//
struct foo7 {
int bigfield:31; /* 32-bit word 1 begins */
int littlefield:1;
};
struct foo8 {
int bigfield1:31; /* 32-bit word 1 begins /*
int littlefield1:1;
int bigfield2:31; /* 32-bit word 2 begins */
int littlefield2:1;
};
// C11 and C++14 may pack foo9 tighter
struct foo9 {
int bigfield1:31; /* 32-bit word 1 begins */
int bigfield2:31; /* 32-bit word 2 begins */
int littlefield1:1;
int littlefield2:1; /* 32-bit word 3 begins */
};
// 需要24个字节
struct foo10 {
char c;
struct foo10 *p;
short x;
};
// 只有16个字节
struct foo11 {
struct foo11 *p; /* 8 bytes */
short x; /* 2 bytes */
char c; /* 1 byte */
char pad[5]; /* 5 bytes */
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment