c - 改进 32 位机器上结构的内存对齐

标签 c memory padding

纠正下面错误的结构对齐。

typedef struct{ 
char *string; // 4 byte (type of address int)

char temp; // 1 byte

short pick; // 2 byte

char temp2; // 1 byte

}hello;
  • 字符串 = 4
  • 临时 + 选择 + temp2(偏移量 7)= 1+2+1

给出答案,良好的对齐是

char *string; // 4 byte (type of address int)

short pick; // 2 byte

char temp; // 1 byte

char temp2; // 1 byte
  • 字符串 = 4
  • 选择 + temp + temp2(偏移量 7)= 2+1+1

无法理解 temp2 应该位于偏移量 7 而不是 8 的原因。怎么办?请帮忙

最佳答案

+---+---+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
+---+---+---+---+---+---+---+---+
|    string     | pick  | t1| t2|
+---+---+---+---+---+---+---+---+

使用 t1 表示 temp,使用 t2 表示 temp2,这是修改后的布局。 t2 的偏移量为 7。

对于 n 字节数量按 n 字节对齐的系统上的原始结构,布局将是:

+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B |
+---+---+---+---+---+---+---+---+---+---+---+---+
|    string     | t1|pad| pick  | t2|pad|pad|pad|
+---+---+---+---+---+---+---+---+---+---+---+---+

这是因为4字节指针需要4字节对齐,所以该结构体的数组需要每个成员都是4字节的倍数。

因此,在原始结构中,t2 的偏移量将为 8,而不是 7。

关于c - 改进 32 位机器上结构的内存对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19486517/

相关文章:

c - 如何正确释放哈希表上的元素

c - 文件阅读作为一种资源

c - C 预处理器的 Null 指令有什么意义?

html - Chrome 的 CSS Margin 问题?

java - AES/CBC/PKCS5Padding Java 加密错误 - javax.crypto.BadPaddingException : Given final block not properly padded

MySQL 连接器 C API 无法连接到 MySQL 服务器

python - Cherrypy 中的内存消耗

linux - Java销售过程中令人困惑的内存报告

python - 在sklearn python中拟合GaussianMixture时如何处理内存错误?

html - 在 Wordpress 上更改标题高度