关于内存对齐示例的困惑

Confusion about a memory alignment example

在阅读一些关于内存对齐知识的帖子时,我有一个关于 What is aligned memory allocation?,@dan04 的好答案的问题。

阅读他给出的例子,

 0 1 2 3 4 5 6 7
|a|a|b|b|b|b|c|d|  bytes
|       |       |  words

The problem is that on some CPU architectures, the instruction to load a 4-byte integer from memory only works on word boundaries. So your program would have to fetch each half of b with separate instructions.

为什么不能(可以吗?)直接读取包含b的4个字节(一个字,假设32位)?

例如,如果我想要b

 0 1 2 3 4 5 6 7
|a|a|b|b|b|b|c|d|  bytes
    |       |      a word(assume it's 32 bit, get b directly)

阅读 1 个单词从 address 2 开始。

如果我想要a

 0 1 2 3 4 5 6 7
|a|a|b|b|b|b|c|d|  bytes
|       |          a word

读取从address 0开始的1个单词并获取前2个字节并丢弃后2个字节。

如果我想要 cd

 0 1 2 3 4 5 6 7
|a|a|b|b|b|b|c|d|  bytes
        |       |  a word

address 4 开始读取 1 个单词并获取最后 2 个字节并丢弃前 2 个字节。

然后好像不需要对齐这肯定是不正确的..


一定是我理解错了什么或者缺乏其他知识,请大家指正..

"Why can't (Can it?) read the 4 bytes(a word, assume 32bits) directly that contains b?"
您已经在上面引用的答案。关键是"on word boundaries"。这与 "in word size" 不同。 IE。这些 CPU 只能准确地从 N*wordwidth 读取字宽,而不能从 N*wordwidth+2.

读取字宽

字边界(仅适用于上述平台)是字宽的干净倍数。 0、4、8、12...但不是 2、6、10...

从评论中提取你的措辞,是的。
这些 CPU 只能从地址 0、4、8、12、16 等读取。
例如。地址 0-3 中的一个字,地址 4-7 中的一个字。 (注意添加的 12。)