On this page

An array in machine code is just a base and an index; element size sets the scale factor, not a hardware type.

In lesson 10, we introduced stack frames and return addresses. The next layer is contiguous data in memory: arrays, arrays of structs, and the addressing formula shared by both mov and lea. In this lesson, I break down [base + index*scale + disp], the SIB byte, and why a C99 array parameter becomes a pointer.

Mental Model: An Address Instead of a Container

What it looks like in C99 What happens in hardware
An array can be passed to a function by value An array parameter is a pointer; only an 8-byte address is copied
&buf passes by reference &buf is a plain address value of type int32_t (*)[1000]
a[i] is a single array operation The address is computed as base + i*4, then a dword is read or written
lea loads data lea computes the address and never touches memory
An array of structs needs special addressing Fields sit at fixed displacements; the scale equals the struct size

Effective Address and SIB

The CPU computes an operand’s address using:

A=B+I⋅S+D A = B + I \cdot S + D
where
AA
resulting computed address.
BB
base from a register.
II
index from a register.
SS
scale factor, one of 1, 2, 4, or 8.
DD
displacement disp, a signed constant.

This result is the effective address. In x86-64 machine encoding, scale, index, and base are packed into the SIB byte.

The max_array.asm testbed finds the maximum key in an array of {key, tag} structs:

max_array.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; max_array.asm — maximum key in a struct array {key, tag} up to sentinel -1.
; GDB inspects .scan_probe: edx holds the current key.

default rel

%define SYS_EXIT 60
%define SENTINEL -1

section .data
    align 4
    values: dd 3, 100, 17, 101, 9, 102, 42, 103, 8, 104, -1, 0

section .text
    global _start

; ------------------------------------------------------------------------------
; int32_t asm_max_array(const struct pair *arr)
; Input:     rdi = address of first {int32 key; int32 tag} struct, key == -1 ends
; Output:    eax = maximum key before sentinel -1
; Clobbers:  rax, rcx, rdx, r8, flags (caller-saved)
; ------------------------------------------------------------------------------
asm_max_array:
    mov eax, dword [rdi]

    xor ecx, ecx
    inc rcx

.loop:
    mov edx, dword [rdi + rcx * 8]

.scan_probe:
    cmp edx, SENTINEL
    je .done

    mov r8d, dword [rdi + rcx * 8 + 4]
    cmp edx, eax
    jle .next
    mov eax, edx

.next:
    inc rcx
    jmp .loop

.done:
    ret

_start:
    lea rdi, [values]
    call asm_max_array
    mov edi, eax

    ; syscall: exit(asm_max_array(values))
    mov eax, SYS_EXIT
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits

Disassembly shows two accesses to the same struct:

  401007:	8b 14 cf             	mov    edx,DWORD PTR [rdi+rcx*8]
  40100f:	44 8b 44 cf 04       	mov    r8d,DWORD PTR [rdi+rcx*8+0x4]

In the ModR/M byte, mod picks register vs. memory and displacement width (disp8, disp32, or none), reg encodes the source or destination register, and r/m encodes the second operand; REX.R adds the high bit to reg.

The line mov r8d, [rdi + rcx*8 + 4] is included solely to demonstrate reading the tag field at offset +4; its result isn’t used afterward.

  • 8b — opcode for mov r32, r/m32.
  • 14 — ModRM: mod=00, reg=010 (edx), r/m=100, signaling that SIB follows.
  • cf — SIB: scale=11 (scale 8), index=001 (rcx), base=111 (rdi).
  • 44 on the second mov — REX.R prefix extending reg to r8d.
  • 04 at the end — disp8: offset of the tag field inside the 8-byte struct.

Memory layout of the struct array and bit-level encoding of the second read:

values (struct { int32_t key; int32_t tag; }, 8 bytes):
     ┌────────┬────────┬────────┬────────┬────────┐
     │ key=3  │tag=100 │ key=17 │tag=101 │  ...   │
     └────────┴────────┴────────┴────────┴────────┘
      +0      +4       +8      +12      +16
       ▲               ▲        ▲
      rdi             rcx=1   disp8 +4

Bytes `44 8b 44 cf 04` — reading `tag` of element `rcx = 1`:
  44  REX.R   R=1 extends reg field to r8d
  8b  opcode  mov r32, r/m32
  44  ModR/M  mod=01 (+disp8), reg=000 (r8d), r/m=100 (SIB follows)
  cf  SIB     scale=11 (×8), idx=001 (rcx), base=111 (rdi)
  04  disp8   +4 bytes (tag field)

asm_max_array assumes the array is non-empty and contains at least one element before the -1 sentinel: the first element is loaded before the loop.

The scale field is two bits wide and encodes only four multipliers:

scale (2 bits) Multiplier
00b ×1
01b ×2
10b ×4
11b ×8

The CPU has no idea what type an element is: scale is just a free multiplier. For an int32_t array you set it to 4; for an 8-byte struct, you set it to 8.

GDB shows both the array contents and the sentinel check:

(gdb) break asm_max_array.scan_probe
Breakpoint 1 at 0x40100a: file max_array.asm, line 34.
(gdb) run
Starting program: .../build/max_array

Breakpoint 1, asm_max_array.scan_probe () at max_array.asm:34
34	    cmp edx, SENTINEL
(gdb) print/d $edx
$1 = 17
(gdb) x/12dw &values
0x402000 <values>:	3	100	17	101
0x402010:	9	102	42	103
0x402020:	8	104	-1	0
  • $1 = 17 — the first key after the initial element: rcx = 1, so edx holds 17.
  • dd emits key, tag pairs; 42, 103 is the fourth struct, which becomes the maximum.
  • -1, 0 — the sentinel in the key field; cmp edx, 0xffffffff terminates the loop.

exit(42) returns 42. The scale of 8 here reflects the struct size, not the size of int32_t.

lea: Computing an Address Without Reading Memory

lea computes an address without issuing a memory read. The lea_math.asm testbed builds two addresses from the cells array:

lea_math.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; lea_math.asm — lea computes base + index*scale + disp without memory access.
; Checkpoints after_index and after_scale are inspected by GDB.

default rel

%define SYS_EXIT 60

section .data
    align 4
    cells: dd 10, 20, 30, 40, 50, 60, 70, 80

section .text
    global _start

; ------------------------------------------------------------------------------
; _start — two lea instructions with different scales; exits with cells[5].
; Input:     none
; Output:    does not return; exit code 60
; Clobbers:  rax, rbx, rcx, rdx, rsi, rdi, r11 (flags untouched)
; ------------------------------------------------------------------------------
_start:
    lea rbx, [cells]
    mov rcx, 3

    lea rax, [rbx + rcx * 4 + 8]

after_index:
    mov edx, dword [rax]

    lea rsi, [rbx + rcx * 8]

after_scale:
    mov edi, edx

    ; syscall: exit(cells[5])
    mov eax, SYS_EXIT
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits

Both formulas appear verbatim in machine code:

  401000:	48 8d 1d f9 0f 00 00 	lea    rbx,[rip+0xff9]        # 402000 <cells>
  40100c:	48 8d 44 8b 08       	lea    rax,[rbx+rcx*4+0x8]
  401013:	48 8d 34 cb          	lea    rsi,[rbx+rcx*8]
  • 48 8d 44 8b 08 — lea rax, [rbx + rcx*4 + 8]: SIB=8b sets scale 4, index rcx, base rbx, and disp8=8.
  • 48 8d 34 cb — lea rsi, [rbx + rcx*8]: SIB=cb sets scale 8 with the same base and index.
  • Scale is an arbitrary multiplier of 1, 2, 4, or 8; it isn’t tied to any element type.

GDB confirms both address calculations and shows that no memory read happened during lea:

(gdb) break after_index
Breakpoint 1 at 0x401011: file lea_math.asm, line 30.
(gdb) break after_scale
Breakpoint 2 at 0x401017: file lea_math.asm, line 35.
(gdb) run
Starting program: .../build/lea_math

Breakpoint 1, after_index () at lea_math.asm:30
30	    mov edx, dword [rax]
(gdb) print/x $rax
$1 = 0x402014
(gdb) print/d $rax - $rbx
$2 = 20
(gdb) x/1dw $rax
0x402014:	60
(gdb) continue
Continuing.

Breakpoint 2, after_scale () at lea_math.asm:35
35	    mov edi, edx
(gdb) print/d $rsi - $rbx
$3 = 24
(gdb) x/8dw &cells
0x402000 <cells>:	10	20	30	40
0x402010:	50	60	70	80
  • $1 = 0x402014 — rax right after lea: the address of cells[5], before memory is read.
  • $2 = 20 — rax - rbx, byte offset to cells[5].
  • x/1dw $rax prints 60: the value waiting at that address for the upcoming mov edx, [rax].
  • $3 = 24 — rsi - rbx for scale 8 when rcx = 3.
  • 0x402014 points to cells[5], so the exit status is 60.

Array Parameters: Array Decay

array_decay.c passes the exact same buffer to two functions—one declared with an array parameter, the other with a pointer parameter:

array_decay.c
/* SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 */

/* array_decay.c — parameter int32_t a[1000] in C99 is a pointer, and &buf is an address value. */

#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

#define COUNT 1000u

int32_t sum_array(int32_t a[COUNT], size_t n)
{
    int32_t total = 0;
    size_t i = 0;

    for (i = 0; i < n; i++) {
        total += a[i];
    }

    return total;
}

int32_t sum_pointer(const int32_t *a, size_t n)
{
    int32_t total = 0;
    size_t i = 0;

    for (i = 0; i < n; i++) {
        total += a[i];
    }

    return total;
}

int main(void)
{
    static int32_t buf[COUNT];
    size_t i = 0;

    for (i = 0; i < COUNT; i++) {
        buf[i] = (int32_t)i;
    }

    printf("sizeof buf = %zu\n", sizeof buf);
    printf("sizeof &buf = %zu\n", sizeof &buf);
    printf("sizeof &buf[0] = %zu\n", sizeof &buf[0]);
    printf("sum_array = %" PRId32 "\n", sum_array(buf, COUNT));
    printf("sum_pointer = %" PRId32 "\n", sum_pointer(buf, COUNT));

    return 0;
}

Running it prints the sizes and sums:

sizeof buf = 4000
sizeof &buf = 8
sizeof &buf[0] = 8
sum_array = 499500
sum_pointer = 499500
  • sizeof buf is 4000: inside main, it’s a genuine array of 1,000 int32_ts.
  • sizeof &buf is 8: type int32_t (*)[1000] points to the whole array, yet is still an 8-byte value.
  • sizeof &buf[0] is also 8: the address of an element and the address of the array are the same size.
  • Both sums match: 499500 = 0 + 1 + ... + 999.

Converting an array name into a pointer to its first element is called array decay. GDB shows the result in debug symbols:

main: buf[1000] (4000 bytes) ──► sum_array(buf, 1000)
                                   │
                                   ▼ address only (8 bytes in rdi)
(gdb) ptype sum_array
type = int (int32_t *, size_t)
(gdb) ptype sum_pointer
type = int (const int32_t *, size_t)
  • The first line describes sum_array: the declaration int32_t a[COUNT] became int32_t *.
  • The second describes sum_pointer; the only difference is const.

At -O2, both functions compile to the exact same loop (.p2align directives omitted):

"sum_array":
	test	rsi, rsi
	je	.L4
	lea	rdx, [rdi+rsi*4]
	xor	eax, eax
.L3:
	add	eax, DWORD PTR [rdi]
	add	rdi, 4
	cmp	rdi, rdx
	jne	.L3
	ret
.L4:
	xor	eax, eax
	ret

sum_pointer emits identical instructions under labels .L9 and .L10. The size 1000 vanished with the array type: the function receives only an address and a length, and taking sizeof on the parameter would yield the pointer size.

Common Pitfalls

  1. “Taking sizeof inside a function gives the array’s size.”
    Fact: ptype sum_array prints int (int32_t *, size_t), whereas sizeof buf in main is 4000.
    Cause: a parameter written int32_t a[1000] is adjusted to a pointer on function entry, discarding the element count.
    Fix: pass the length as a separate size_t n parameter and never apply sizeof to an array parameter.

  2. "& passes an array by reference."
    Fact: sizeof &buf and sizeof &buf[0] are both 8, and sum_pointer takes an ordinary pointer.
    Cause: C99 has no reference parameters; an address is just a value copied on call.
    Fix: treat pointers as numeric addresses, pass sizes explicitly, and don’t expect reference semantics from &.

  3. "lea reads memory at the computed address."
    Fact: at after_index, rax = 0x402014, print/d $edx is 0, while x/1dw $rax prints 60.
    Cause: lea only calculates the effective address; loading memory happens on the next instruction, mov edx, [rax].
    Fix: use lea for address arithmetic and don’t expect loaded data in the destination register without a separate mov.

  4. “The SIB scale always equals the element size.”
    Fact: lea rsi, [rbx + rcx*8] with rcx = 3 gives cells + 24, even though cells holds 4-byte elements.
    Cause: scale is an arbitrary multiplier of 1, 2, 4, or 8; the CPU has no knowledge of element types.
    Fix: pick the scale to match your element stride (4 for int32_t, 8 for a pair of int32_ts) and verify the resulting address in GDB.

Lab

Goal. Build array_walk.asm to find the maximum key in an array of structs and compute an element’s address using lea.

Contract and requirements.

  • Data is an array of {int32 key; int32 tag} structs; the trailing sentinel struct has key = -1.
  • The search function takes the array address and returns the maximum key.
  • A second operation for index 3 computes the struct’s address with lea and reads its tag.
  • Exit status is the low byte of the sum of the maximum key and that tag.
  • Use different displacements within the same addressing formula to access key and tag.

Verification criteria.

  1. ./build/array_walk; echo $? outputs the expected byte for your dataset.
  2. objdump -d -M intel build/array_walk contains a SIB byte with scale 8 and disp = 4.
  3. In GDB at the comparison label, the register holds the next key, not a tag.
  4. In GDB after lea, address - base equals 3 * 8 = 24.
  5. In GDB, inspecting the computed address reads the tag of the fourth struct.
Hints, expected output, and walkthrough

For keys 3, 17, 9, 42, 8 with tags 100..104, the maximum key is 42 and the fourth struct’s tag is 103. The exit code is 145.

  • A struct of two int32_ts is 8 bytes.
  • key sits at offset 0.
  • tag sits at offset 4.
  • Index scale is 8.

If the scale accidentally remains 4, GDB will show base + 12 instead of base + 24, reading right into the middle of the wrong struct.

Watch for a telltale bug: exiting with just the tag instead of the sum means your comparison is reading tag rather than key. Always check both the computed address and the value stored there.

The sentinel must stay distinct from any valid key; at key = -1, the loop exits before reading the trailing struct’s tag.

Testbed sources, Makefile, and automated tests for this lesson: lessons/11-addressing-arrays.

Summary

  1. An element address is computed via base + index*scale + disp.
  2. The SIB byte packs the scale, index register, and base register.
  3. scale only supports 1, 2, 4, or 8 and is not tied automatically to any type.
  4. lea calculates an address without accessing memory.
  5. In a C99 function parameter, an array decays into a pointer, so its length must be passed separately.
  6. &buf is an address value, not a reference; only the address is copied on call.
Bridge to the Next Lesson
Memory is now addressable, yet our programs still talk to the kernel only through exit. In lesson 12, I move to system calls: how syscall switches privilege rings, why it clobbers rcx and r11, what a file descriptor actually is, and how the VFS maps it to an inode.