A string in memory has no “length” field—just bytes and a trailing zero.
Lesson 13 ended with string pointers on the startup stack. Strings themselves are raw bytes, while numbers in registers are binary values. Three functions bridge the two, and in this lesson I walk through them instruction by instruction—along with a look at how a signed char combined with a negative idiv remainder yields a negative index and SIGSEGV.
Mental Model: Bytes and Arithmetic
| What it looks like in C99 | What happens in hardware |
|---|---|
| A string “knows” its length | Memory holds only bytes; the end is marked by a zero byte |
strlen is a built-in operation |
A loop running cmp byte [...], 0 and incrementing a counter |
char is just a character |
On x86-64, char is signed: byte 0xC3 reads as -61 |
The % remainder is always non-negative |
In C99, the remainder takes the sign of the dividend |
atoi and itoa are type conversions |
Multiply or divide by 10, offset by the ASCII code '0' |
strlen: Length Lives in Memory
asm_strlen walks byte by byte until it hits zero and returns the step count. No length field exists anywhere in memory.
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; strlen.asm — string length up to the trailing null byte without libc.
default rel
section .text
global asm_strlen
; ------------------------------------------------------------------------------
; size_t asm_strlen(const char *s)
; Input: rdi = s
; Output: rax = number of bytes before the first null byte
; Clobbers: rax, flags (caller-saved)
; ------------------------------------------------------------------------------
asm_strlen:
xor eax, eax
test rdi, rdi
jz .done
.loop:
cmp byte [rdi + rax], 0
je .done
inc rax
jmp .loop
.done:
ret
section .note.GNU-stack noalloc noexec nowrite progbitsIn disassembly, the loop takes five instructions:
7: 80 3c 07 00 cmp BYTE PTR [rdi+rax*1],0x0
b: 74 05 je 12 <asm_strlen.done>
d: 48 ff c0 inc rax
10: eb f5 jmp 7 <asm_strlen.loop>
12: c3 retcmp BYTE PTR [rdi+rax*1],0x0compares the current byte to zero;BYTE PTRpins the operand width to one byte.je .doneexits the loop on the null terminator.inc raxadvances both the counter and the index—no separate cursor pointer is needed.jmp .looploops back to the comparison; instead of a “loop while non-zero” branch, it pairsjewith an unconditionaljmp.
GDB verifies the contract on "hello, world":
(gdb) break asm_strlen
(gdb) run
...
(gdb) x/s $rdi
0x5555555560f4: "hello, world"
(gdb) finish
$1 = 12x/s prints the string at rdi, and finish (lesson 05) runs to ret and prints rax = 12. The ellipsis skips earlier testbed calls to strlen.
atoi and itoa: Divisor and Character Code
A number in memory is a binary value, not a sequence of digits. Forward conversion is atoi, and the reverse is itoa.
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; atoi.asm — parse a decimal string into int64_t without overflow checks.
default rel
section .text
global asm_atoi
; ------------------------------------------------------------------------------
; int64_t asm_atoi(const char *s)
; Input: rdi = s (no leading whitespace; digits and optional leading '-')
; Output: rax = parsed value; stops at first non-digit byte
; Clobbers: rax, rcx, rdi, r8, flags (caller-saved)
; Note: int64_t overflow is not diagnosed
; ------------------------------------------------------------------------------
asm_atoi:
xor eax, eax
xor r8d, r8d
cmp byte [rdi], '-'
jne .digits
mov r8d, 1
inc rdi
.digits:
movzx ecx, byte [rdi]
sub ecx, '0'
cmp ecx, 9
ja .done
imul rax, rax, 10
add rax, rcx
inc rdi
jmp .digits
.done:
test r8d, r8d
jz .ret
neg rax
.ret:
ret
section .note.GNU-stack noalloc noexec nowrite progbitsThe byte is zero-extended via the movzx instruction in movzx ecx, byte [rdi]; otherwise a byte like 0xD0 would become negative. Subtracting '0' maps the character code to 0..9, and cmp ecx, 9 with ja rejects any non-digit. Any byte below '0' (including the null terminator) wraps negative on subtraction, which the unsigned ja branch treats as a huge unsigned number > 9.
asm_itoa mirrors this: dividing by 10 produces the lowest digit in rdx, writes digits from the start of the buffer, and then reverses the character array in place.
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; itoa.asm — format int64_t as a decimal string using unsigned division.
default rel
section .text
global asm_itoa
; ------------------------------------------------------------------------------
; size_t asm_itoa(int64_t value, char *buf)
; Input: rdi = value, rsi = buf
; Output: rax = string length excluding null terminator, buf[rax] = 0
; Clobbers: rax, rcx, rdx, r8, r9, r10, r11, flags (caller-saved)
; ------------------------------------------------------------------------------
asm_itoa:
mov rax, rdi
mov r10, rsi
xor ecx, ecx
xor r9d, r9d
test rax, rax
jns .digits
; INT64_MIN cannot be represented as a signed positive value, so neg leaves
; the exact bit pattern needed as an unsigned magnitude.
mov r9d, 1
neg rax
.digits:
mov r11d, 10
.digit_loop:
xor edx, edx
div r11
add dl, '0'
mov byte [r10 + rcx], dl
inc rcx
test rax, rax
jnz .digit_loop
test r9d, r9d
jz .reverse_prep
mov byte [r10 + rcx], '-'
inc rcx
.reverse_prep:
xor eax, eax
lea rdx, [rcx - 1]
.reverse:
cmp rax, rdx
jae .done
mov r8b, byte [r10 + rax]
mov r11b, byte [r10 + rdx]
mov byte [r10 + rax], r11b
mov byte [r10 + rdx], r8b
inc rax
dec rdx
jmp .reverse
.done:
mov byte [r10 + rcx], 0
mov rax, rcx
ret
section .note.GNU-stack noalloc noexec nowrite progbitsThe division details matter:
xor edx, edxmust precede everydiv r11:divdivides the 128-bit pairrdx:rax, so the high half must be zero.div r11leaves the remainder inrdx, soadd dl, '0'converts it to an ASCII digit.mov byte [r10 + rcx], dlwrites the least significant digit first, building the number backward.- For
INT64_MIN,neg raxyields the bit pattern0x8000000000000000, which as an unsigneduint64_tequals , letting unsigneddivprint its magnitude cleanly. - The reversal pass swaps
buf[0]andbuf[len-1]and walks inward.
Phase 1 (div 10): 123 ─► remainders 3, 2, 1 ─► buf = [ '3' | '2' | '1' | ... ]
Phase 2 (reverse): '3' ◄──► '1' ─► buf = [ '1' | '2' | '3' | 0 ]The testbed checks its output against snprintf across seven values, including INT64_MIN:
$ ./build/strnum
strlen: 4 samples OK, "hello" = 5
itoa: 7 values OK, INT64_MIN = -9223372036854775808
atoi: 5 strings OK, "-1234567890" = -1234567890Where Signed char Breaks Array Indexing
A common misconception says: “a modulo remainder is always non-negative, so an array index can never go below zero.” In C99, that’s false: % keeps the sign of the dividend. A second trap is char: on x86-64 it is signed, so the UTF-8 byte 0xC3 reads as -61.
The ub_signed_char_bad.c testbed places a lookup table at the start of a second page and locks down the preceding page with mprotect(..., PROT_NONE):
const char *key = "\xC3\xA9"; /* letter 'é' in UTF-8, first byte 0xC3 */
...
value = (int32_t)key[0] - 'A';
slot = value % table_size;
printf("key[0] = %d, value = %d, slot = %d\n", key[0], value, slot);
printf("table[%d] = %d\n", slot, table[slot]);table_size is a non-static global with external linkage, so the compiler assumes another translation unit could modify it and keeps a real hardware division:
mov eax, -126
mov edx, -1
idiv DWORD PTR table_size[rip]
...
movsxd rax, DWORD PTR 8[rsp]
lea rax, 0[rbp+rax*4]
mov edx, DWORD PTR [rax+rbx]At -O2, slot is spilled to 8[rsp] after idiv and reloaded with movsxd, while table’s address is assembled from rbp (start of the mmap region—more on mmap in lesson 22) plus rbx (page size), so the read hits [rax+rbx].
mov eax, -126is-61 - 65, the byte value minus'A'.mov edx, -1is-O2’s precomputed sign extension of the negative dividend-126(replacing a runtimecdq).idiv DWORD PTR table_size[rip]dividesedx:eaxby 16, leaving remainder-14inedx.movsxd rax, DWORD PTR 8[rsp]loads the 32-bitslotand sign-extends it to 64 bits, preserving the minus sign;lea rax, 0[rbp+rax*4]then scales the negative index bysizeof(int32_t)and adds it to the table base.
Page 1 (accessible)
table ──► [ table[0] | table[1] | ... | table[15] ]
│
│ −56 bytes (14 × sizeof(int32_t))
▼
Page 0 (PROT_NONE)
[ table[-14] ]
│
└──► SIGSEGV, exit 139Running the binary confirms both the negative remainder and the crash:
$ ./build/ub_signed_char_bad; echo $?
key[0] = -61, value = -126, slot = -14
139GDB pinpoints where the negative index lands:
Program received signal SIGSEGV, Segmentation fault.
0x000055555555513c in main () at ub_signed_char_bad.c:57
57 printf("table[%d] = %d\n", slot, table[slot]);
$1 = -126
$2 = -14
$3 = (int32_t *) 0x7ffff7f7e000
=> 0x55555555513c <main+188>: mov edx,DWORD PTR [rax+rbx*1]$1isvalue,$2isslot.$3is the base address oftable; index-14reads 56 bytes to the left, straight into thePROT_NONEguard page.mov edx,DWORD PTR [rax+rbx*1]istable[slot]in Intel syntax.- Exit code
139is termination bySIGSEGV(128 + 11).
Common Pitfalls
-
"
strlenreturns the array size."
Fact:char buf[4] = {'a', 'b', 'c', 'd'};without a null byte makesasm_strlenkeep scanning past the array until a stray zero byte stops it.
Cause: the function knows nothing about buffer capacity and trusts only the null terminator.
Fix: always null-terminate explicitly (buf[3] = '\0') or pass the buffer length separately. -
"
itoaproduces digits backward."
Fact: for123, the buffer contains"321"right after the division loop.
Cause:divyields the least significant digit first, while writes advance from the start of the buffer.
Fix: reverse the populated slice in place before appending the null terminator. -
"
INT64_MINprints as garbage."
Fact:negonINT64_MINyields the exact same bit pattern0x8000000000000000.
Cause: there is no positive 64-bit signed counterpart; signed arithmetic overflows.
Fix: divide the negated bit pattern as an unsigned 64-bit value viadiv, asasm_itoadoes, and handle the minus sign separately. -
“An array index from
%can never be negative.”
Fact:(int32_t)key[0] - 'A'for byte0xC3is-126, and-126 % 16is-14.
Cause:charis signed, and C99’s%operator keeps the dividend’s sign.
Fix: cast bytes tounsigned charbefore doing arithmetic and normalize negative remainders ((slot + size) % size).
Lab
Goal. Extend asm_itoa into asm_itoa_base(int64_t value, uint32_t base, char *buf) to format integers in any base from 2 to 16.
Contract and requirements.
- Inputs: value, base
2..16, and a buffer of at least 66 bytes. - Output: string length excluding the null terminator;
buf[length] = 0. - For bases above 10, digits
10..15use lowercase lettersa..f. INT64_MINmust format accurately in base 10 and base 16.- An invalid base returns
0without writing to the buffer.
Verification criteria.
make -C lessons/14-strings-numbers build teststays green.- Your test compares output against
snprintffor bases 2, 8, 10, and 16. gdb -q --nx -batch -ex 'break asm_itoa_base' -ex run -ex 'set $buf = $rdx' -ex finish -ex 'x/s $buf' ./build/strnumsaves the buffer pointer on entry (the third argument sits inrdx), runs toret, and prints the formatted string—forvalue = 255and base 16,"ff". At the entry breakpoint the buffer isn’t filled yet, sox/8cb $rdxshows garbage; to inspect the pre-reversal digits, break at the label right before the reversal loop and runx/8cb $buf.echo $?for the test harness equals0; crashing onINT64_MINis unacceptable.
Hints, expected output, and walkthrough
For value = 255, expected strings are "11111111" (base 2), "377" (8), "255" (10), and "ff" (16). For value = -255 in base 16, "-ff".
The algorithm stays the same: divide the unsigned magnitude by base, look up the character in "0123456789abcdef", then reverse in place. Keep the base in a register so div divides by a register rather than an immediate.
If base 2 truncates at "1", verify the loop checks the quotient rather than the remainder. If INT64_MIN prints a double minus sign or garbage digits, signed and unsigned logic got mixed up (for example, using signed idiv instead of unsigned div after emitting '-').
Testbed sources, Makefile, and automated tests for this lesson: lessons/14-strings-numbers.
Summary
- A string in memory is raw bytes terminated by
0; no length is stored alongside it. strlenloops until the zero byte while incrementing an index.atoiaccumulates digits by multiplying by 10 and subtracting'0'.itoadivides by 10, writes digits least-significant first, and reverses the buffer.INT64_MINmust be handled via its unsigned magnitude rather than signed negation alone.- A signed
charcombined with a negative%remainder produces a negative index andSIGSEGV.
RDX:RAX pair: 128-bit mul and div, the cqo instruction, and the #DE exception that Linux turns into SIGFPE without a single floating-point number in sight.