Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 40 ยท Arrays, Strings and Structs

Structs, Padding and Alignment

See how a C struct becomes field offsets in assembly, the alignment rules that create padding, and how structs are passed and returned on x86-64.

A C struct has no representation of its own at the machine level. It is a block of bytes, and each field is just a number: the offset from the start of the block. To read p->y the compiler emits a memory operand with a displacement, such as [rdi+8]. There are no field names, no types and no bounds in the final code; all that survives is arithmetic on addresses.

The interesting part is how those offsets are chosen. Hardware prefers each value to sit at an address that is a multiple of its size, so compilers leave gaps called padding. In this lesson you will see how offsets are computed, how to predict sizeof, how structs look in compiler output, and how they travel through function calls. For the C-side view of the same topic, read Padding and Alignment and Structures; here we care about what the assembly sees.

Fields are offsets

Take a small struct and a function that uses it:

C
struct Particle {
    int    id;      // offset 0
    float  mass;    // offset 4
    double x;       // offset 8
    double y;       // offset 16
};                  // sizeof = 24

double move_x(struct Particle *p, double dx) {
    p->x += dx;
    return p->x;
}

The pointer p arrives in rdi and dx in xmm0. At -O2 GCC emits roughly:

NASM
move_x:
    addsd  xmm0, QWORD PTR [rdi+8]     ; dx + p->x
    movsd  QWORD PTR [rdi+8], xmm0     ; p->x = result
    ret                                ; result is still in xmm0

The field x is simply [rdi+8]. If you read p->mass you would see movss xmm0, DWORD PTR [rdi+4]: a 4-byte load at offset 4. An array of structs combines this with the scaled addressing from the previous lesson. ps[i].y is base + i*24 + 16, and since 24 is not a legal scale, the compiler computes 3*i first:

NASM
get_y:                                  ; double get_y(const struct Particle *ps, long i)
    lea    rax, [rsi+rsi*2]             ; 3 * i
    movsd  xmm0, QWORD PTR [rdi+16+rax*8]   ; base + 16 + (3*i)*8 = base + 24*i + 16
    ret

This is the reason struct sizes matter in disassembly. The odd multiplier in front of a scaled load is often sizeof(struct) in disguise.

Alignment and padding

On x86-64 and ARM64 Linux, a basic type's alignment equals its size: char 1, short 2, int and float 4, long, double and pointers 8. The layout rules are mechanical:

  1. Place each field at the next offset that is a multiple of its alignment, inserting padding if needed.
  2. The struct's own alignment is the largest alignment among its fields.
  3. The total size is rounded up to a multiple of the struct's alignment (tail padding), so that in an array every element is correctly aligned.

Take this struct, whose fields are in an unlucky order:

C
struct Mixed { char tag; int id; char flag; double score; short n; };
flowchart LR
  A["tag, 0"] --> B["pad, 1 to 3"] --> C["id, 4 to 7"] --> D["flag, 8"] --> E["pad, 9 to 15"] --> F["score, 16 to 23"] --> G["n, 24 to 25"] --> H["tail pad, 26 to 31"]

Struct Mixed holds 16 bytes of data but occupies 32: the gaps before id, before score, and at the end are padding.

The fields add up to 1 + 4 + 1 + 8 + 2 = 16 bytes, yet sizeof is 32. Sort the fields by decreasing alignment and almost all of the padding vanishes:

C
struct Sorted { double score; int id; short n; char tag; char flag; };   // size 16

Let the real compiler confirm these numbers. The next example runs on the site's C runner (GCC on x86-64 Linux) and prints every offset with offsetof.

C offsetof and sizeof for two field orders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output should show Mixed at 32 bytes with id at 4, flag at 8, score at 16 and n at 24, and Sorted at 16 bytes. The next demo implements the same three rules in JavaScript, so you can try your own field lists, and then writes values into a byte buffer to show where the padding really is.

JS A struct layout calculator with a byte dump

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The dump makes the little-endian layout visible: id = 0x11223344 appears as 44 33 22 11 at offsets 4 to 7, and the double 1.5 as 00 00 00 00 00 00 f8 3f at offsets 16 to 23. The padding bytes are real memory; their contents are unspecified, which is why comparing two structs with memcmp is unreliable. The JavaScript dump shows them as .. because the model knows they are not data.

The rules above are those of the common 64-bit ABIs (System V on Linux and macOS, Windows x64, ARM64). They are not part of the C language itself: a 32-bit x86 target aligns double to 4 inside structs, for example. When layout matters for files or networks, use fixed-width types and either check with offsetof and static_assert or define the byte format explicitly. __attribute__((packed)) removes the padding, but then fields can be misaligned, which compilers handle with slower or byte-wise accesses on some targets.

Passing and returning structs

How does a struct travel into and out of a function? The System V x86-64 rules are about size and content:

  • A struct of 16 bytes or less is split into 8-byte pieces. Integer pieces go in the next free integer argument registers (rdi, rsi, ...); pieces made only of float/double fields go in xmm registers.
  • A larger struct (or one with awkward fields such as unaligned ones) is passed in memory: the caller copies it onto the stack.
  • Returned structs follow the same split: up to 16 bytes come back in rax/rdx (or xmm0/xmm1 for floating-point pieces). A larger result is written to memory the caller provides, and its address is passed as a hidden first argument in rdi; the function returns that same pointer in rax.

Here are the three cases, with typical -O2 output:

C
struct Pair { long a; long b; };          // 16 bytes
struct Big  { long a, b, c; };            // 24 bytes

long sum_pair(struct Pair p) { return p.a + p.b; }
struct Pair make_pair(long a, long b) { return (struct Pair){a, b}; }
struct Big make_big(long a, long b, long c) { return (struct Big){a, b, c}; }
long sum_big(struct Big p) { return p.a + p.b + p.c; }
NASM
sum_pair:                       ; p.a arrives in rdi, p.b in rsi
    lea  rax, [rdi+rsi]
    ret

make_pair:                      ; returned in rax:rdx
    mov  rax, rdi
    mov  rdx, rsi
    ret

make_big:                       ; rdi = hidden pointer to the result, then a, b, c
    mov  rax, rdi               ; return the pointer
    mov  QWORD PTR [rdi], rsi
    mov  QWORD PTR [rdi+8], rdx
    mov  QWORD PTR [rdi+16], rcx
    ret

sum_big:                        ; the 24-byte argument sits on the stack above the return address
    mov  rax, QWORD PTR [rsp+8]
    add  rax, QWORD PTR [rsp+16]
    add  rax, QWORD PTR [rsp+24]
    ret

Notice that make_big has one more argument than the C source suggests: a, b and c are in rsi, rdx and rcx, because rdi is taken by the hidden result pointer. Windows x64 uses a simpler rule: a struct of exactly 1, 2, 4 or 8 bytes is passed in a register as if it were an integer, and any other size is passed by pointer to a copy made by the caller. ARM64 passes structs up to 16 bytes in registers and larger ones by reference. The full tables are in Calling Conventions.

A practical consequence: passing large structs by value costs a copy, which is why C programmers pass pointers (const struct Big *) for anything bigger than a couple of machine words.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the offset of int b in struct S { char a; int b; } on x86-64 Linux?

    An int has alignment 4, so b must start at a multiple of 4. The char occupies offset 0, three bytes of padding follow, and b sits at offset 4 (the struct's size is 8).
  2. 2. Why does a struct get tail padding at its end?

    The size is rounded up to a multiple of the struct's alignment so that the next array element begins at an aligned address.
  3. 3. Which ordering of fields normally minimizes padding?

    Placing 8-byte fields first, then 4-byte, 2-byte and 1-byte ones lets each field land naturally on its alignment boundary, leaving gaps only at the end.
  4. 4. A System V x86-64 function returns a 24-byte struct. How is it returned?

    Results larger than 16 bytes use a hidden pointer argument in rdi pointing at caller-provided memory; the function fills it and returns the same pointer in rax.

Summary

  • A struct is a block of bytes; fields are accessed as [base + offset], and the offsets are decided at compile time.
  • Each field is aligned to its own size (on common 64-bit ABIs), the struct is aligned to its largest field, and its size is rounded up to that alignment.
  • Reordering fields from largest to smallest alignment usually shrinks the struct; offsetof and sizeof show the real layout.
  • Arrays of structs compile to scaled loads with a size-dependent multiplier plus a field displacement.
  • On System V x86-64, structs up to 16 bytes travel in registers; larger ones go through memory, and large return values use a hidden pointer in rdi.

Next: ARM64 (AArch64) Basics, where we leave x86 behind and meet a processor with 31 general registers and fixed-size instructions.