Docsity

C Structs and Data Alignment: Understanding Structures and Memory Allocation in C, Lecture notes of Object Oriented Programming

Toggle sidebar
bg1
Sean Barker
C Structs
1
a
r
i next
0 16 24 32
struct rec {
int a[4];
size_t i;
struct rec* next;
};
struct rec x;
struct rec y;
x.i = 5;
x.a[1] = 2;
x.next = &y;
y = x; // copy full struct
struct rec* z;
z = &y; // just a pointer copy
// form 1
(*z).i = 7; // NOT z.i = 7;
// form 2 (preferred)
z->i = 7;
Sean Barker
typedef
2
// give type T another name: U
typedef T U;
// example: defines a type “struct rec”
// and typedefs it with another name “rec”
typedef struct rec {
...
} rec;
rec x; // now can omit “struct”
x.i = 5;
rec* p = (rec*) malloc(sizeof(rec));
p->i = 3;
pf3
pf4

Partial preview of the text

Download C Structs and Data Alignment: Understanding Structures and Memory Allocation in C and more Lecture notes Object Oriented Programming in PDF only on Docsity!

Sean Barker

C Structs

1

a

r

i next

struct rec { int a[4]; size_t i; struct rec next; };* struct rec x; struct rec y; x.i = 5; x.a[1] = 2; x.next = &y; y = x; // copy full struct struct rec* z; z = &y; // just a pointer copy // form 1 (*z).i = 7; // NOT z.i = 7; // form 2 (preferred) z->i = 7;

typedef

// give type T another name: U typedef T U; // example: defines a type “struct rec” // and typedefs it with another name “rec” typedef struct rec { ... } rec; rec x; // now can omit “struct” x.i = 5; rec* p = (rec*) malloc(sizeof(rec)); p->i = 3;

Sean Barker

Linked List Example

3 .L11: # loop: movslq 16(%rdi), %rax # i = M[r+16] movl %esi, (%rdi,%rax,4) # M[r+4i] = val movq 24(%rdi), %rdi # r = M[r+24] testq %rdi, %rdi # Test r jne .L11 # if !=0 goto loop void set_val (struct rec r, int val) { while (r) { int i = r->i; r->a[i] = val; r = r->next; } } Register Value %rdi r %rsi val struct rec { int a[4]; int i; struct rec* next; }; Element i r i next 0 16 24 32 a**

Data Alignment

*struct S1 { char c; int i[2]; double v; } p;

Unaligned Data

c i[0] i[1] v p p+1 p+5 p+9 p+

Aligned Data

c 3 bytes^ i[0] i[1] 4 bytes v

p+0 p+4 p+8 p+16 p+

Mul3ple of 4 Mul3ple of 8

Mul3ple of 8 Mul3ple of 8

Floating Point: YMM/XMM Registers

n 16 single-byte integers n 8 16-bit integers n 4 32-bit integers n 4 single-precision floats n 2 double-precision floats n 1 single-precision float n 1 double-precision float