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:
- resulting computed address.
- base from a register.
- index from a register.
- scale factor, one of 1, 2, 4, or 8.
- 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:
; 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 progbitsDisassembly 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 formov r32, r/m32.14—ModRM:mod=00,reg=010(edx),r/m=100, signaling thatSIBfollows.cf—SIB:scale=11(scale 8),index=001(rcx),base=111(rdi).44on the secondmov—REX.Rprefix extendingregtor8d.04at the end —disp8: offset of thetagfield 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, soedxholds17.ddemitskey, tagpairs;42, 103is the fourth struct, which becomes the maximum.-1, 0— the sentinel in thekeyfield;cmp edx, 0xffffffffterminates 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:
; 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 progbitsBoth 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=8bsets scale 4, indexrcx, baserbx, anddisp8=8.48 8d 34 cb—lea rsi, [rbx + rcx*8]:SIB=cbsets 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—raxright afterlea: the address ofcells[5], before memory is read.$2 = 20—rax - rbx, byte offset tocells[5].x/1dw $raxprints60: the value waiting at that address for the upcomingmov edx, [rax].$3 = 24—rsi - rbxfor scale 8 whenrcx = 3.0x402014points tocells[5], so the exit status is60.
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:
/* 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 = 499500sizeof bufis4000: insidemain, it’s a genuine array of 1,000int32_ts.sizeof &bufis8: typeint32_t (*)[1000]points to the whole array, yet is still an 8-byte value.sizeof &buf[0]is also8: 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 declarationint32_t a[COUNT]becameint32_t *. - The second describes
sum_pointer; the only difference isconst.
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
retsum_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
-
“Taking
sizeofinside a function gives the array’s size.”
Fact:ptype sum_arrayprintsint (int32_t *, size_t), whereassizeof bufinmainis4000.
Cause: a parameter writtenint32_t a[1000]is adjusted to a pointer on function entry, discarding the element count.
Fix: pass the length as a separatesize_t nparameter and never applysizeofto an array parameter. -
"
&passes an array by reference."
Fact:sizeof &bufandsizeof &buf[0]are both8, andsum_pointertakes 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&. -
"
leareads memory at the computed address."
Fact: atafter_index,rax = 0x402014,print/d $edxis0, whilex/1dw $raxprints60.
Cause:leaonly calculates the effective address; loading memory happens on the next instruction,mov edx, [rax].
Fix: useleafor address arithmetic and don’t expect loaded data in the destination register without a separatemov. -
“The
SIBscale always equals the element size.”
Fact:lea rsi, [rbx + rcx*8]withrcx = 3givescells + 24, even thoughcellsholds 4-byte elements.
Cause:scaleis 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 forint32_t, 8 for a pair ofint32_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 haskey = -1. - The search function takes the array address and returns the maximum
key. - A second operation for index
3computes the struct’s address withleaand reads itstag. - Exit status is the low byte of the sum of the maximum
keyand thattag. - Use different displacements within the same addressing formula to access
keyandtag.
Verification criteria.
./build/array_walk; echo $?outputs the expected byte for your dataset.objdump -d -M intel build/array_walkcontains aSIBbyte with scale 8 anddisp = 4.- In GDB at the comparison label, the register holds the next
key, not atag. - In GDB after
lea,address - baseequals3 * 8 = 24. - In GDB, inspecting the computed address reads the
tagof 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. keysits at offset0.tagsits at offset4.- 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
- An element address is computed via
base + index*scale + disp. - The
SIBbyte packs the scale, index register, and base register. scaleonly supports 1, 2, 4, or 8 and is not tied automatically to any type.leacalculates an address without accessing memory.- In a C99 function parameter, an array decays into a pointer, so its length must be passed separately.
&bufis an address value, not a reference; only the address is copied on call.
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.