NOTE
3.6 Memory Alignment
Machine word length, memory addressing, alignment boundaries, why alignment is needed, data-structure alignment, address alignment, and references.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Machine Word Length
1.1. Address Bus and Data Bus
- The CPU addresses memory through the address bus, while memory transfers data to the CPU through the data bus.
- The number of address-bus bits determines the memory size: for example, with an 8-bit address bus, addresses
[0, 255]can be addressed, for a total of 256 B. Memory beyond 256 B cannot be used. - The data bus determines how much data can be transferred at one time: for example, to operate on 1 B at a time, an 8-bit data bus is required.
- This is also called the machine word length.

2. Memory Addressing
- Memory module
3. What Is Memory Alignment?
To ensure efficient program execution, the compiler arranges data of various types at suitable addresses and makes them occupy suitable lengths. Memory alignment requires both the data-storage address and the number of occupied bytes to be integer multiples of the alignment boundary.
4. How to Determine the Alignment Boundary
- Type size.
- Platform maximum alignment boundary.
- The alignment boundary is the smaller of the two values above.

- This balances performance and memory usage.
4.1. Struct Alignment Boundary
5. Why Is Memory Alignment Needed?
5.1. Platform Reasons
Not every hardware platform can access arbitrary data at arbitrary addresses.
5.2. Performance Reasons
To access unaligned memory, the processor needs to issue two memory accesses; aligned memory only needs one memory access.
6. How to Use Memory Alignment
6.1. Data-Structure Alignment
Depends on type size guarantees and alignment guarantees.
-
Size guarantees

-
Alignment guarantees

6.1.1. Tools
- layout
- optimize
6.1.2. Examples
- If fields inside a struct require too much padding, they can be reordered so the fields are packed more tightly, reducing wasted memory.
- Avoid placing a zero-sized field as the last field of a struct, as this can waste memory.
6.2. Memory Address Alignment
The address of a variable is an integer multiple of the alignment value of that variable’s type.
uintprt(unsafe.Pointer(&x)) % unsafe.Alignof(x) == 0



Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub