ASSEMBLY / CHAPTER 10
Bounded byte scans and sentinel searches
MasterCheck valid extent before searching for a terminator.
By the end of this chapter
- Test bounds before loads
- Distinguish found positions from the count boundary
- Avoid reading beyond a nonterminated buffer
The idea
A zero-terminated string convention does not make an arbitrary buffer safe to scan indefinitely. A bounded scan receives both a base address and the number of readable bytes. Before each load, verify that the index is below that count. Empty input then performs no access, and a missing terminator returns the boundary rather than walking into unrelated memory.
Choose a return contract that represents both outcomes. Returning the zero-byte index when found and count otherwise is useful because count is not a valid element index. The caller must compare with count before treating the result as a found position. A bound check protects the stated extent only if the caller supplied a valid base/count pair; assembly does not verify that underlying memory contract.
; RDI points to bytes 65, 66, 67, 0; RSI = 4.
; Return first zero-byte index, or RSI if none is found.
xor eax, eax
.scan:
cmp rax, rsi
jae .done
cmp byte [rdi+rax], 0
je .done
inc rax
jmp .scan
.done:RAX = 3.
The loop checks the bound first, then finds zero at the fourth byte’s zero-based index.
Try it yourself
Adapt the scan to find a requested byte and return count when it is absent.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING