如果内存是字节可寻址的,为什么我们需要对齐填充?

发布于 2024-12-03 15:52:30 字数 129 浏览 1 评论 0原文

既然我们可以单独寻址内存的每个字节,为什么编译器要格外小心以确保结构及其成员与内存中的 32 位边界对齐? 我在这里可能是错的,但是在 32 位系统上,从 0x0800 开始获取 4 个字节是不是和从 0x0801 开始获取 4 个字节一样快?

Since we can address every byte of memory individually, why do compilers take extra care to make sure that structs and it's members align to 32-bit borders in memory?
I could be wrong here, but on a 32-bit system, is it not just as fast to get 4 bytes starting from say 0x0800, as it is from 0x0801?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

两相知 2024-12-10 15:52:30

在大多数架构上,对自然对齐的数据类型执行读/写速度更快。在某些系统上,如果您尝试访问某些未对齐的类型,则会生成异常(即大多数情况下崩溃)。因此,一般来说,除非您有充分的理由不这样做,否则您总是希望保持自然对齐。

另请参阅相关 SO 问题和解答:

On most architectures it is faster to perform read/write on naturally aligned data types. On some systems it will generate an exception (i.e. crash in most cases) if you try to access certain types when they are misaligned. So in general you always want to maintain natural alignment unless you have a very good reason not to.

See also related SO questions and answers:

与往事干杯 2024-12-10 15:52:30

摘自维基百科

例如,当计算机的字大小为 4 字节(一个字节表示 8 位)时,要读取的数据应该位于 4 的倍数的内存偏移处。如果不是这种情况,例如数据如果从第 14 个字节而不是第 16 个字节开始,那么计算机必须读取两个 4 字节块并在读取请求的数据之前进行一些计算,否则可能会产生对齐错误。即使前一个数据结构在第 14 个字节结束,下一个数据结构也应该从第 16 个字节开始。在两个数据结构之间插入两个填充字节,将下一个数据结构与第 16 个字节对齐

内存必须是4 字节的倍数,以便更快地访问并减少计算为了更好的性能
因此,如果内存是地址字节可寻址的,在大多数情况下通常是 4 字节块,那么我们知道下一个地址将从哪里开始,例如如上所述,如果您最终得到 14 字节(应该为 16 字节 4*4 = 16) 那么您就知道必须使用多少填充 16-14 = 2 字节填充。这就是为什么在未对齐的内存中使用填充的原因。

Taken from wikipedia:

For example, when the computer's word size is 4 bytes (a byte meaning 8 bits), the data to be read should be at a memory offset which is some multiple of 4. When this is not the case, e.g. the data starts at the 14th byte instead of the 16th byte, then the computer has to read two 4-byte chunks and do some calculation before the requested data has been read, or it may generate an alignment fault. Even though the previous data structure ends at the 14th byte, the next data structure should start at the 16th byte. Two padding bytes are inserted between the two data structures to align the next data structure to the 16th byte

The memory has to be multiple of 4 bytes for faster access and to reduce computation for better performance.
so if the memory is address byte addressable usually of 4 bytes chunks in most of cases then we know where the next address is going to start e.g. as explained above also if you end up with 14 bytes (that should be 16 bytes 4*4 = 16) then you know how much padding you have to use 16-14 = 2 bytes padding. that is why padding is used in misaligned memory.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文