0

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 
  • Does this answer your question? [What registers are preserved through a linux x86-64 function call](https://stackoverflow.com/questions/18024672/what-registers-are-preserved-through-a-linux-x86-64-function-call) – Joseph Sible-Reinstate Monica Jul 15 '20 at 03:47
  • 1
    `movq $b, %rdx` puts the *address* of the symbol into RDX. It's not a load. So `cmpq %rdx, %rcx` will always clear ZF because those two addresses (or 0 and the address) are constant. Use a debugger to look at register values while you single step to catch mistakes like this where and instruction doesn't do what you thought. – Peter Cordes Jul 15 '20 at 03:58
  • @JosephSible-ReinstateMonica b is only used to store %rdx because it will be cleared when printf is run. I use it in: movq $b, %r8 movq %rdx, (%r8) #rdx is saved in b – user3194396 Jul 15 '20 at 04:00

0 Answers0