assemblyx86nasmcalling-convention

x86 NASM Crash - Iterate over string


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


Solution

  • printf uses eax for the return value