So, when there is no data, I can visualize the memory like this:
Each row represents a 4-byte region. For example, the row starting at 0x00 represents addresses 0x00–0x03, and the row starting at 0x04 represents addresses 0x04–0x07.
Suppose we define a structure like this:
Let's assume a contains 'A' and x contains the 4-byte value 0x12345678.
With alignment, I understand the memory layout would look like this:
Here, the 4-byte int starts at 0x04, which is a 4-byte boundary, so all four bytes of the int fit inside one 4-byte region.
Without alignment, the 4-byte value could theoretically start immediately after the char:
Here, the int starts at 0x01 and crosses the 0x04 boundary. In the simplified 32-bit memory model we're discussing, the CPU may need two memory accesses to obtain the complete 4-byte value, followed by additional work to combine the bytes.
So I think the main advantage of alignment is that it can make memory access simpler and more efficient.
The trade-off is that we use some extra memory for padding. In this example, we waste 3 bytes of memory to ensure that the 4-byte int starts at a 4-byte boundary.
Code:
Address Byte 1 Byte 2 Byte 3 Byte 4
----------------------------------------------
0x00 empty empty empty empty
0x04 empty empty empty empty
0x08 empty empty empty empty
0x0C empty empty empty empty
Suppose we define a structure like this:
C:
struct test {
char a;
int x;
};
With alignment, I understand the memory layout would look like this:
Code:
Address Byte 1 Byte 2 Byte 3 Byte 4
----------------------------------------------------
0x00 'A' padding padding padding
0x04 0x12 0x34 0x56 0x78
0x08 empty empty empty empty
Without alignment, the 4-byte value could theoretically start immediately after the char:
Code:
Address Byte 1 Byte 2 Byte 3 Byte 4
----------------------------------------------------
0x00 'A' 0x12 0x34 0x56
0x04 0x78 empty empty empty
0x08 empty empty empty empty
So I think the main advantage of alignment is that it can make memory access simpler and more efficient.
The trade-off is that we use some extra memory for padding. In this example, we waste 3 bytes of memory to ensure that the 4-byte int starts at a 4-byte boundary.
Last edited: