How to iterate over individual characters of a string in x86 assembly and print them?
global _main ; declare _main entry point
extern _printf ; extern method
section .data
string: db 'Iterate over this string #test', 0
character: db '_', 0
endStr: db 'Ended.', 0
section .text
_main:
lea eax, string ;load address of string to eax
loop:
mov cl, [eax] ; access [eax] in memory, save char to cl
test cl, cl ; check if zero terminator
jz end ; exit if 0
mov [character], cl ; write char to memory (character)
push character ; print character
call _printf
add esp, 4 ; clear stack
inc eax ; increment address
jmp loop ; loop again
end:
push endStr ; print 'Ended.'
call _printf
add esp, 4 ; clear stack
ret ; exit
My current program crashes after printing the first character of the string, "I". There is no error outputted to the console.
Thanks for any help in advance.
printf
useseax
for the return value. Consult calling convention documentation about what registers are preserved. Quick fix: dopush eax
before thepush character
and apop eax
before theinc eax
. PS: learn to use a debugger. Also this is 32 bit code so don't tag x86-64putchar
is probably more sensible thanprintf
, but note that its argument is the character itself rather than a pointer.