0

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.

3
  • 2
    printf uses eax for the return value. Consult calling convention documentation about what registers are preserved. Quick fix: do push eax before the push character and a pop eax before the inc eax. PS: learn to use a debugger. Also this is 32 bit code so don't tag x86-64
    – Jester
    Commented Jul 5 at 15:44
  • What OS is this for? They use different calling conventions. Stack alignment is another issue to watch for. Commented Jul 5 at 17:41
  • For outputting a single character, putchar is probably more sensible than printf, but note that its argument is the character itself rather than a pointer. Commented Jul 5 at 17:44

1 Answer 1

-4

if you know how to, try to use a debugger to step through the program recommended debuggers Linux: gdb Windows: x64dbg

and i think the problem is that you are trying to clear the stack even though i think the printf does that by itself, depending on the architect and everything you can try to know how to use it by compiling an hello world with debug info and decompiling it

New contributor
cat1000101 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • 2
    There are no mainstream systems where variadic function like printf use a callee-pops convention. That would require the caller to pass extra info on the size of args, because it can't be inferred from the format string. C requires printf to work correctly even if args are passed beyond what the format string references. Commented Jul 14 at 0:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.