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

  • eax is not a call-preserved register. After the call to printf, eax is garbage.

    The immediate best solution is to use register esi instead.

    I'm actually in a little bit of trouble here because of the 16 byte stack alignment required for modern glibc, and I don't know the calling convention rules well enough to preserve it. But that doesn't seem to be why you are crashing.