Compute a string's length with equ $ - msg in NASM
Let NASM 2.16.03 count a string for you: len equ $ - msg after the data, so write and the buffer never disagree.
Counting characters by hand is how a trailing newline gets lost. NASM can do it at assembly time: $ is the address of the current position, so len equ $ - msg, placed directly after the string, is the byte count of everything between. NASM 2.16.03 evaluates it once, and it becomes a constant with no storage. This program prints a greeting using that length as the write count.
global _start
section .data
msg db "Hello, NASM", 10
len equ $ - msg ; must sit right after msg
section .text
_start:
mov eax, 1 ; write
mov edi, 1 ; stdout
mov esi, msg
mov edx, len
syscall
mov eax, 60
xor edi, edi
syscall$ nasm -f elf64 hello.asm && ld hello.o -o hello && ./hello
Hello, NASMThe value is 12: eleven characters plus the newline written as 10. The placement is the whole trick. Add another db between msg and the equ and the length silently grows to include it. equ also makes len an immediate, so mov edx, len is a constant load, not a memory read. In a .bss buffer the same pattern does not apply; use resb and an explicit size. In GNU as the equivalent is len = . - msg.