打印
[应用相关]

是什么内存对齐?

[复制链接]
63|1
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
jf101|  楼主 | 2024-2-27 23:32 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
是什么内存对齐?


在C语言中,内存对齐是按照一定的规则在内存中排列数据,从而使数据的起始地址符合特定的要求。根据 The GNU C Reference Manual 的 2.4.5 Size of Structures 一章所提到的:

The size of a structure type is equal to the sum of the size of all of its members, possibly including padding to cause the structure type to align to a particular byte boundary. The details vary depending on your computer platform, but it would not be atypical to see structures padded to align on four- or eight-byte boundaries. This is done in order to speed up memory accesses of instances of the structure type.

一个结构体可能会包含一些填充部分(padding)来使之对齐到一个特定的字节边界(particular byte boundary),实际上就是开头我们描述的使数据的起始地址要符合特定的要求。比如我们有 a 和 b 两个数据,都占一个单位的大小,正常情况下我们会将这两个紧挨着一起摆放,如下:

<p>+---+---+---+---+---+</p><p>| 0 | 1 | 2 | 3 | 4 |</p><p>+---+---+---+---+---+</p><p>| a | b | * | * | * |</p><p>+---+---+---+---+---+</p>

可以看到 a 被放在了 0 地址,b 被放在了 1 地址,* 表示其他内容,在这里我们不关注。这种存放顺序也是最符合我们主观常识的方式。然而此时如果我们加个条件,b 元素必须要在能被 4 整除的地址上(0、4、8 ...)才能正常访问,此时元素的摆放顺序就改变了:

<p>+---+---+---+---+---+</p><p>| 0 | 1 | 2 | 3 | 4 |</p><p>+---+---+---+---+---+</p><p>| a | - | - | - | b |</p><p>+---+---+---+---+---+</p>

可以看到在这种情况下,a 仍然是在 0 地址,但 b 却跨过了 3 个元素的空间,被摆放在了 4 地址,中间的 - 就是填充元素,其功能就是把 b 元素挤到 4 这个地址,从而使它可以被正常访问到。

这,就是内存对齐!在上例中,我们可以说 b 元素是 4 字节对齐的。



使用特权

评论回复
沙发
Henryko| | 2024-2-29 22:57 | 只看该作者
单片机是怎么判断有没有内存对齐的啊

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

184

主题

1220

帖子

2

粉丝