STM32 Memory Alignment – Understanding and Solutions

memorystm32

As I'm reading the Mastering STM32 Book, I came across this graphic describing the memory map enter image description here

So what I'm trying to figure out is whether my understanding of memory is wrong, or if the graphic is. It is my understanding that in the figure on the right, the 5th variable (a byte) should be at address 0x20000008. The memory addresses increase from right to left, and top to bottom. So the 1st variable would have bits 7 to 0 at 0x20000000, bits 15 to 8 at 0x20000001, so on so forth. Could someone point me in the right direction if I'm incorrect?

Best Answer

The only thing that is not aligned is the #4 word in the right-hand diagram.

Everything else in both diagrams is aligned on natural boundaries — bytes on byte boundaries (by definition, since it's byte-addressable memory), halfwords on halfword boundaries, and words on word boundaries.


The thing that is really weird about the right-hand diagram is that #4 word does not occupy a contiguous set of bytes, and this may well be a drawing error. For some reason, bytes are numbered right-to-left, but the objects are packed left-to-right. I would have expected those diagrams to look more like this, in which the packing is in the same order as the byte addresses:

Aligned

     3        2        1        0
+--------+--------+--------+--------+
|              word 1               | 0x20000000
+--------+--------+--------+--------+
|////////| byte 3 |   halfword 2    | 0x20000004
+--------+--------+--------+--------+
|              word 4               | 0x20000008
+--------+--------+--------+--------+
|////////| byte 7 | byte 6 | byte 5 | 0x2000000C
+--------+--------+--------+--------+
|/////////////////|   halfword 8    | 0x20000010
+--------+--------+--------+--------+

Unaligned

     3        2        1        0
+--------+--------+--------+--------+
|              word 1               | 0x20000000
+--------+--------+--------+--------+
| word 4 | byte 3 |   halfword 2    | 0x20000004
+--------+--------+--------+--------+
| byte 5 |          word 4          | 0x20000008
+--------+--------+--------+--------+
|   halfword 8    | byte 7 | byte 6 | 0x2000000C
+--------+--------+--------+--------+
|///////////////////////////////////| 0x20000010
+--------+--------+--------+--------+