0

I'm working on x86-64 assembly language on my MacOS on VIM and I'm trying to be able to print the nth number of the fibonacci sequence.

Unfortunately I get an infinite loop that says "The 1th value is 1"

I have been trying different methods but I'm unable to resolve this.

Is there any way to fix this?

.file "fibonacci.s"

.data
n:
    .quad 10
first:
    .quad 0
second:
    .quad 1
result:
    .quad 0
i:
    .quad 0

printf_line:
    .string "The %ldth value is %ld\n"

.globl main
.type main, @function

.text

main:
    pushq %rbp
    movq %rsp, %rbp

    movq $printf_line, %rdi
    movq $n, %rsi
    movq $n, %rdx
    xorl %eax, %eax
    call printf

    xorq %rdi, %rdi
    xorq %rsi, %rsi
    xorq %rdx, %rdx

loop:
    cmpq n(%rip), %rdi
    jg loop_end

    cmpq $1, %rdi
    jle if_cond_true

    movq first(%rip), %rax
    addq second(%rip), %rax
    movq %rax, result(%rip)

    movq second(%rip), %rax
    movq %rax, first(%rip)
    movq result(%rip), %rax
    movq %rax, second(%rip)

    jmp end_if_cond

if_cond_true:
    movq %rdi, result(%rip)

end_if_cond:
    movq %rdi, %rdx
    movq result(%rip), %rsi
    movq $printf_line, %rdi
    xorl %eax, %eax
    call printf

    incq %rdi
    jmp loop

loop_end:
    leave
    ret

Anon
  • 31
  • 3
  • [What registers are preserved through a linux x86-64 function call](https://stackoverflow.com/q/18024672) - even your own code overwrites your RDI loop counter in passing an arg to printf. Use a debugger to single-step and look at reg values. Use call-preserved regs for your loop if you want to call printf inside it. You have other bugs, too, like loading the address instead of value for `n` at the top of `main`, unlike with `cmp` where you correctly access the value. Unless that first line is printing the addresses on purpose? There's no comment in the source. – Peter Cordes Jun 05 '23 at 17:53

0 Answers0