OutOfBrainExcepction
OutOfBrainExcepction

Reputation: 23

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.

Upvotes: 0

Views: 75

Answers (3)

Joshua
Joshua

Reputation: 43188

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.

Upvotes: 0

OutOfBrainExcepction
OutOfBrainExcepction

Reputation: 23

According to Jester in the comments below:

printf uses eax for the return value.

Upvotes: 0

cat1000101
cat1000101

Reputation: 1

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

Upvotes: -4

Related Questions