I am trying to write a program in x86_64 assembly to print an inputted number N out N times Example:
N? 3
NUM=3
NUM=3
NUM=3
but instead I am getting an infinite loop of such:
N? 3
NUM=3
NUM=3
NUM=3
NUM=3
...
I think it has something to do with the fact that printf clears some registers after being run which is messing with my while loop somehow.
I have tried saving the two registers I use for comparison in the while loop (%rdx and %rcx) but my while loop still runs indefinitely.
.data
.comm a,8 # long a;
.comm b,8 # long b;
.text
str0:
.string "N? "
str1:
.string "%ld"
str2:
.string "NUM=%ld\n"
.globl main
main: # main()
pushq %rbp # Save frame pointer
movq %rsp, %rbp #
movq $str0, %rdi #printf("N?");
movq $0, %rax
movq $str1, %rdi #scanf("%ld", &a);
movq $a, %rsi
movq $0, %rax
call scanf
movq $0, %rdx #b
movq $a, %rcx
while: cmpq %rdx, %rcx #as long as rdx is less than rcx, run loop
jle afterw
movq $str2, %rdi # printf("NUM=%ld\n");
movq $a, %rsi
movq (%rsi),%rsi
movq $0, %rax
movq $b, %r8
movq %rdx, (%r8) #rdx is saved in b
call printf
movq $b, %rdx #restore $b in %rdx
movq $a, %rcx #restore $a in rcx
addq $1, %rdx #increment rdx until it reaches rcx/$a/the inputted value N
jmp while
afterw:
leave
ret