I am trying to make a for loop in assembly.
Here is what I am trying to achieve written in C:
#include <stdio.h>
int main(){
    for(int i = 0; i < 10; i++){
        printf("%d\n", i);
    }
    return 0;
}
This is what my assembly code looks like:
.text
.globl _main
loop0.0:
  movl -4(%rbp), %eax           #eax = i
  cmpl $10, %eax                #compare i with 10
  jg loop0.2                    #if 10 > i goto loop0.2
loop0.1:
  leaq _format(%rip), %rdi      #set arg1 to format
  movl -4(%rbp), %esi           #set arg2 to i
  call _printf                  #printf(format, i)
  movl -4(%rbp), %esi           #set esi to i
  addl $1, %esi                 #esi++
  movl %esi, -4(%rbp)           #i = esi
  jmp loop0.0
_main:                           #int main
  pushq %rbp
  movq %rsp, %rbp
  movl $0, -4(%rbp)              #i = 0
  jmp loop0.0                    #goto  loop0.0
  loop0.2:
  xor %eax, %eax                 #return 0;
  popq %rbp
  retq
.data
  _format:
    .asciz "%d\n"
When I run this code, I get the current output:
0
2
2
2
2
2
2
and so on
Why is it that my code displays 0 first (as it should), and then two for an infinite amount of time? I hope my comments are accurate as this is what I think each line of code does.
 
     
     
    