From Unaligned Memory Accesses
Unaligned memory accesses occur when you try to read N bytes of data
starting from an address that is not evenly divisible by N (i.e. addr
% N != 0). For example, reading 4 bytes of data from address 0x10004
is fine, but reading 4 bytes of data from address 0x10005 would be an
unaligned memory access.
The size of int
is 4 bytes, size of short
is 2 bytes, size of char
is 1 byte (64 bit system).
Let's assume the starting address as 0x0000.
So, int i
occupies from 0x0000 to 0x0003.
char c
is stored at 0x0004 (since, address is divisible by 1).
Assume there is no 1 byte padding after char c
, Then, short s
will be stored at 0x0005, which is not divisble by 2. This causes unaligned memory accesses.
To prevent this, we add 1 byte padding after char c
. After padding 1 byte, short s
will be stored ar 0x0006, which is divisble by 2.