Lecture Slides 06 065-Structsalign
Lecture Slides 06 065-Structsalign
Multiple of 4 Multiple of 8
Multiple of Multiple of
8 Structures and Alignment
8
University of Washington
Alignment Principles
Aligned Data
Primitive data type requires K bytes
Address must be multiple of K
Aligned data is required on some machines; it is advised on IA32
Treated differently by IA32 Linux, x86-64 Linux, and Windows!
What is the motivation for alignment?
Alignment Principles
Aligned Data
Primitive data type requires K bytes
Address must be multiple of K
Aligned data is required on some machines; it is advised on IA32
Treated differently by IA32 Linux, x86-64 Linux, and Windows!
Motivation for Aligning Data
Physical memory is accessed by aligned chunks of 4 or 8 bytes (system-
dependent)
Inefficient to load or store datum that spans quad word boundaries
Also, virtual memory is very tricky when datum spans two pages (later…)
Compiler
Inserts padding in structure to ensure correct alignment of fields
sizeof() should be used to get true size of structs
Multiple of 4 Multiple of 8
Multiple of 8 Multiple of 8
Structures and Alignment
University of Washington
IA32 Linux: K = ?
K = 4; double aligned like a 4-byte data type
Saving Space
Put large data types first:
struct S1 { struct S2 {
char c; double v;
int i[2]; int i[2];
double v; char c;
} *p1; } *p2;
Unfortunately, doesn’t
satisfy requirement
v i[0] i[1] c that struct’s total size
p2+0 p2+8 p2+16 is a multiple of K
Structures and Alignment
University of Washington
Arrays of Structures
Satisfy alignment requirement struct S2 {
for every element double v;
int i[2];
char c;
} a[10];
a[0] • • • a[i] • • •
a+0 a+12i
i 2 bytes v j 2 bytes
a+12i a+12i+8
short get_j(int idx)
{ # %eax = idx
return a[idx].j; leal (%eax,%eax,2),%eax # 3*idx
// return (a + idx)->j; movswl a+8(,%eax,4),%eax # a+12*idx+8
}
Structures and Alignment