Heterogeneous data structure
Structs
-
Consider the following structure declaration:
struct rec {int i;int j;int a[2];int *p;}struct rec *r;- Suppose variable
r
is in register %rdi, the following code copies elementr->i
to elementr->j
movl (%rdi), %eax // get r->imovl %eax, 4(%rdi) // Store in r->j-
The offset of field
i
is 0, the address of this field is simply the value ofr
. -
The offset of field
j
is 4, the address of this field = address ofr
+ offset 4. -
Suppose variable
r
is in register %rdi, long integer variablei
is in register%rsi
, we can generate the pointer value&(r->a[i])
with the single instruction:
leaq 8(%rdi,%rsi,4), %rax //Set %rax to &r->a[i] - Suppose variable
-
Example 2:
struct test {short *p;struct {short x;short y;} s;struct test *next;}; -
Example 3:
Union
Data alignment
- Many computer systems place restrictions on the allowable addresses for the primitive data types, requiring that the address for some objects must be a multiple of some valueK (typically 2, 4, or 8). Such alignment restrictionssimplify the design of the hardware forming the interface between the processor and the memory system.
Example 1
struct S1 { int i; char c; int j;}
-
Suppose the compilter use the minimal 9-byte allocation, diagrammed as follows:
-
Then it would be impossible to satisfy the 4-byte alignment requirement for both fields i (offset 0) and j (offset 5). Instead, the compiler inserts a 3-byte gap (shown here as shaded in blue) between fields c and j:
As a result, j has offet 8, the overall structure size is 12 bytes
Example 2
struct S2 { int i; int j; char c; }