Padding for Struct Members
Learn more about how structures are represented in memory.
We'll cover the following...
Introduction
Let’s revisit a previous example for a structure definition.
typedef struct
{
char x;
int y;
} TExample;
Assume the following declaration:
TExample p;
When representing it in memory, we may assume the following layout:
x
starts at the beginning ofp
.x
is 1 byte long.y
starts 1 byte afterx
.
However, recall that when we inspected the memory layout by printing the memory addresses, we saw something like this:
&p = 499487560
&(p.x) = 499487560
&(p.y) = 499487564
The difference between p.x
and p.y
is 4 bytes, not 1 byte, as we may assume since sizeof(char)
= 1.
Therefore, the correct memory drawing is below. Notice the changes marked in purple.
The memory drawing looks as if the type of x
was int
, not char
, even if we wrote char
.
Explanation
This behavior happens because the compiler adds padding to certain structure members. Padding means that it allocates more space than needed. The compiler does this to ensure the memory is aligned, which reduces the time it takes for the CPU to read from it.
Some architectures enforce padding, while others do not. For example, in x86
, the CPU can read memory locations that are not aligned, but reading them is slower and not preferred.
The CPU likes to read memory in blocks called words.
- If the memory address is aligned, the CPU can read it in one cycle.
- If the memory address is not aligned, it must read it in two or more cycles.
Let’s say the word size is 4 bytes. Then, the CPU can read 4 bytes at a time. Let’s ...