For loop isn't counting right

Question!

I have problem with for loop in x86 assembly under Linux with NASM as assembler and gcc as linker. Here is my code:

    SECTION .data
    msg: dw "working",10, 0
    msglen: equ $-msg
    msgtwo: dw "not",10,0
    msgtwolen: equ $-msgtwo
SECTION .text
    global main

main:
    push ebp    ; making the stack
    mov ebp, esp    ; -|-
    mov ecx, 0x0    ; counter
    mov ebx, 0xA    ; value that should be reached
    cmp ecx, ebx    ; checkif i < 10
    jne notzero ; jump if i < 10
    je zero ; jump if i == 0
notzero:
    inc ecx         ; ecx++
    mov eax, 4
    mov ebx, 1
    mov ecx, msgtwo
    mov edx, msgtwolen
    int 80h
zero:
    mov eax, 4  ; write sys call
    mov ebx, 1  ; stdout
    mov ecx, msg    ; msg to print
    mov edx, msglen ; msg len
    int 80h     ; interrupt
    mov esp, ebp    ;destroing the stack
    pop ebp      ; -|-

I have comment everything so it will be more easy for you to figure out what I'm trying to do. Here is the problem. When the program finish it should print "working", when counting it should print "not", it's printing only once "not", not 9 times. Here is the output:

not
working


Answers

You never jump back to the loop head, which should probably be the cmp instruction, but you also clobber the counter value in ecx, so you would need to deal with that issue as well.



In order to have a loop, you need a branch/jump back to the top of the loop from the bottom, which you do not have(it goes just before zero).

Also, you don't need the jne just before nonzero: it will fall through to there if the je fails.



This video can help you solving your question :)
By: admin