On this page

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.

strlen.asm
; 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 progbits

In 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                   	ret
  • cmp BYTE PTR [rdi+rax*1],0x0 compares the current byte to zero; BYTE PTR pins the operand width to one byte.
  • je .done exits the loop on the null terminator.
  • inc rax advances both the counter and the index—no separate cursor pointer is needed.
  • jmp .loop loops back to the comparison; instead of a “loop while non-zero” branch, it pairs je with an unconditional jmp.

GDB verifies the contract on "hello, world":

(gdb) break asm_strlen
(gdb) run
...
(gdb) x/s $rdi
0x5555555560f4:	"hello, world"
(gdb) finish
$1 = 12

x/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.

atoi.asm
; 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 progbits

The 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.

itoa.asm
; 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 progbits

The division details matter:

  • xor edx, edx must precede every div r11: div divides the 128-bit pair rdx:rax, so the high half must be zero.
  • div r11 leaves the remainder in rdx, so add dl, '0' converts it to an ASCII digit.
  • mov byte [r10 + rcx], dl writes the least significant digit first, building the number backward.
  • For INT64_MIN, neg rax yields the bit pattern 0x8000000000000000, which as an unsigned uint64_t equals 2632^{63}, letting unsigned div print its magnitude cleanly.
  • The reversal pass swaps buf[0] and buf[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" = -1234567890

Where 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):

c
    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, -126 is -61 - 65, the byte value minus 'A'.
  • mov edx, -1 is -O2’s precomputed sign extension of the negative dividend -126 (replacing a runtime cdq).
  • idiv DWORD PTR table_size[rip] divides edx:eax by 16, leaving remainder -14 in edx.
  • movsxd rax, DWORD PTR 8[rsp] loads the 32-bit slot and sign-extends it to 64 bits, preserving the minus sign; lea rax, 0[rbp+rax*4] then scales the negative index by sizeof(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 139

Running the binary confirms both the negative remainder and the crash:

$ ./build/ub_signed_char_bad; echo $?
key[0] = -61, value = -126, slot = -14
139

GDB 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]
  • $1 is value, $2 is slot.
  • $3 is the base address of table; index -14 reads 56 bytes to the left, straight into the PROT_NONE guard page.
  • mov edx,DWORD PTR [rax+rbx*1] is table[slot] in Intel syntax.
  • Exit code 139 is termination by SIGSEGV (128 + 11).

Common Pitfalls

  1. "strlen returns the array size."
    Fact: char buf[4] = {'a', 'b', 'c', 'd'}; without a null byte makes asm_strlen keep 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.

  2. "itoa produces digits backward."
    Fact: for 123, the buffer contains "321" right after the division loop.
    Cause: div yields 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.

  3. "INT64_MIN prints as garbage."
    Fact: neg on INT64_MIN yields the exact same bit pattern 0x8000000000000000.
    Cause: there is no positive 64-bit signed counterpart; signed arithmetic overflows.
    Fix: divide the negated bit pattern as an unsigned 64-bit value via div, as asm_itoa does, and handle the minus sign separately.

  4. “An array index from % can never be negative.”
    Fact: (int32_t)key[0] - 'A' for byte 0xC3 is -126, and -126 % 16 is -14.
    Cause: char is signed, and C99’s % operator keeps the dividend’s sign.
    Fix: cast bytes to unsigned char before 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..15 use lowercase letters a..f.
  • INT64_MIN must format accurately in base 10 and base 16.
  • An invalid base returns 0 without writing to the buffer.

Verification criteria.

  1. make -C lessons/14-strings-numbers build test stays green.
  2. Your test compares output against snprintf for bases 2, 8, 10, and 16.
  3. gdb -q --nx -batch -ex 'break asm_itoa_base' -ex run -ex 'set $buf = $rdx' -ex finish -ex 'x/s $buf' ./build/strnum saves the buffer pointer on entry (the third argument sits in rdx), runs to ret, and prints the formatted string—for value = 255 and base 16, "ff". At the entry breakpoint the buffer isn’t filled yet, so x/8cb $rdx shows garbage; to inspect the pre-reversal digits, break at the label right before the reversal loop and run x/8cb $buf.
  4. echo $? for the test harness equals 0; crashing on INT64_MIN is 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

  1. A string in memory is raw bytes terminated by 0; no length is stored alongside it.
  2. strlen loops until the zero byte while incrementing an index.
  3. atoi accumulates digits by multiplying by 10 and subtracting '0'.
  4. itoa divides by 10, writes digits least-significant first, and reverses the buffer.
  5. INT64_MIN must be handled via its unsigned magnitude rather than signed negation alone.
  6. A signed char combined with a negative % remainder produces a negative index and SIGSEGV.
Bridge to the Next Lesson
Remainder already exposed signs, while division so far stayed within 64-bit operands. In lesson 15, I unpack the 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.