C811 of 55
0 XP
  1. Hook
  2. Play
  3. Predict
  4. Name it
  5. Check
  6. Explain

C8 · Lesson 11 · Structs, unions and data layout

How a compiler lays out structs, and why the layout matters

A temperature sensor sends a 7-byte record: a 1-byte channel, a 4-byte timestamp and a 2-byte reading. Declare a C struct with those three fields in that order and sizeof says 12, not 7. Read the reading straight out of a network packet and you get 11,265 instead of 300. Both surprises come from rules about where bytes are allowed to sit in memory, and every program that talks to hardware or a network has to know them.

  • pts is an array of three struct point { short x; short y; int color; }, 8 bytes each: x at offset 0, y at 2 and color at 4.
  • The loop adds up the y fields. Each lh t2, 2(t0) reads a y; addi t0, t0, 8 steps to the next struct.
  • Watch the memory window: each struct is two halfwords and a word. The y values are −4, 10 and 5, so a0 ends at 11.

Predict

How many bytes does struct { char c; int t; short r; } take on RV32?

Name it

Alignment

A value of size 2, 4 or 8 bytes is aligned when its address is a multiple of its size. Hardware fetches aligned values in one access; a misaligned word can straddle two cache lines or two memory words, so many processors either trap on it or handle it slowly (RISC-V allows either). Compilers therefore keep every field aligned.

The struct layout rules

  1. Fields go in the order they're declared.
  2. Each field starts at the next offset that's a multiple of its alignment (on RV32: char 1, short 2, int and pointers 4, double and long long 8).
  3. The struct's alignment is its largest field's, and its size is rounded up to a multiple of that, so that every element of an array of structs is aligned.

The offset of a field rounds up the current offset o to the alignment a:

offset=a⌈oa⌉

Ordering fields from the largest alignment to the smallest leaves no gaps between them, only the final rounding, which gives the smallest size possible. A field access compiles to the struct's address plus a constant, and element i of an array of structs is at base + i · sizeof.

Unions and bit fields

A union's members all start at offset 0 and overlap; its size is the largest member's, rounded to its alignment. Unions let one stored value be read as different types, such as a word as four bytes. Bit fields (unsigned mode : 3;) pack several small fields into one word; the compiler reads them with shifts and masks.

Packed data and byte order

File formats and network protocols fix their own layouts, with no padding and often big-endian ("network order") multi-byte fields. Code that reads them either copies byte by byte or uses packed structs, and swaps the bytes of each field on a little-endian machine.

Arrays of structs, or structs of arrays

When a loop touches one field of many records, an array of structs drags every record's other fields through the cache too. A struct of arrays, one array per field, packs the field it needs together. The choice changes how many cache lines a loop touches, often by several times.

Worked example

How big is struct { char a; double d; short s; } on RV32, where double aligns to 8? How small does reordering make it?

Show the solution
  1. Place a. a takes offset 0.
  2. Place d. d must start at a multiple of 8, so it sits at 8 to 15 after 7 bytes of padding.
  3. Place s. s takes 16 and 17.
  4. Round the size. The struct's alignment is 8, so the size rounds up from 18 to 24.
  5. Reorder as d, s, a. d at 0, s at 8, a at 10, and the size rounds up from 11 to 16.

Answer 24 bytes as written and 16 reordered: a third smaller, from moving one field.

Worked example

A packet carries a 16-bit length, big-endian, at offset 2: the bytes there are 0x01 then 0x2C. What does lhu from that address read on a little-endian processor, and what's the real length?

Show the solution
  1. What lhu reads. A little-endian load takes the byte at the lower address as the low byte, giving 0x2C01 = 11,265.
  2. What the sender meant. 0x012C = 300.
  3. The fix. Swap the two bytes (ntohs in C), or load them separately with lbu and combine them: (first << 8) | second.
  4. Other fields. Every multi-byte field in a big-endian format needs the same treatment.

Answer lhu reads 0x2C01, which is 11,265; the real length is 0x012C, which is 300.

Worked example

A loop sums one 4-byte field of 1000 records, each 16 bytes. How many 64-byte cache lines does it touch with an array of structs, and with a separate array for that field?

Show the solution
  1. Array of structs. The records fill 16,000 bytes: 16,00064=250lines and the loop uses 4 of every 16 bytes it brings in.
  2. Struct of arrays. The field's array is 4,000 bytes: 4,00064≈63lines every byte of which is used.
  3. Compare. Four times fewer lines, and four times less memory traffic if the data isn't already cached.

Answer 250 lines with an array of structs and about 63 with a separate array for the field.

Check

A struct starts with 3 chars, then a short, then an int.

(a)

At what offset does the short start?

(b)

What's its size?

Check

An array of 12-byte structs starts at 0x2000 (8192). A field sits at offset 6.

(a)

At what address is element 3's field?

(b)

How far does p++ move a pointer to these structs?

Check

recs holds four struct { int id; int value; }. Put the sum of the value fields in a0.

RISC-V RV32IM (base integer plus multiply and divide). End your program with ebreak. Tab indents; press Esc and then Tab to move on.

Check

A union holds char c[5], an int i and a short s.

(a)

What's its size?

(b)

i is set to 11223344. What does c[0] read on a little-endian machine?

Check

A big-endian 16-bit field arrives as the bytes 5 then 44.

(a)

What value did the sender mean?

(b)

What does lhu read from it on RV32?

Check

The next free offset in a struct is o, and the next field has alignment a.

Step 1

At what offset does the field go?

Type it the way you would write it, like 3sin(2πft) or 3*sin(2*pi*f*t). Angles can be in radians or carry a degree sign, like 45°.

Check

Which order of the fields char, int, short, double gives the smallest struct on RV32?

Check

A loop reads one 4-byte field from each of 1000 records of 16 bytes, with 64-byte cache lines.

(a)

How many lines does it touch as an array of structs?

(b)

And with the field in its own array?

Check

A status word in a0 holds a 6-bit field in bits 11:6. Put the field's value in a1.

RISC-V RV32IM (base integer plus multiply and divide). End your program with ebreak. Tab indents; press Esc and then Tab to move on.

Explain why

Why do compilers pad structs instead of packing fields tightly, and when should a programmer pack them anyway?

Practice

Keep practicing

10 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.