Avoiding a bad address error when implementing recursion in assembly

0

I am practicing recursion in assembly with the MIPS instruction set, but I always get a "bad address error"

fibonacci:
   # PROLOGUE
   subu    $sp, $sp, 8
   sw    $ra, 8($sp)
   sw    $fp, 4($sp)
   addu    $fp, $sp, 8

   # BODY
   bgt $a0, 1, rec
   move $v0, $a0
   j ret

rec:
   subu $a0, $a0, 1 #sets a0 = j-1
   subu $s0, $a0, 1 #saves s0 = j-2 for later
   jal  fibonacci         # call fibonacci
   # $v0 == f(j-1)
   move $t0, $v0 # t0 = f(j-1)
   move $a0, $s0 #sets a0 = j-2
   jal fibonacci
   add   $v0, $v0, $t0      # $v0 = f(j-2) + f(j-1) 
ret:
   # EPILOGUE
   move    $sp, $fp
   lw    $ra, ($fp)
   lw    $fp, -4($sp)
   jr     $ra

This code works fine on the inputs 1, 2, but when I try to compute f(3), I get the following:

Exception occurred at PC=0x0040004c
  Bad address in data/stack read: 0x00000004
  Exception 7  [Bad data address]  occurred and ignored

I suspect that the issue has something to do with the 2nd call to fibonacci. But what would be the issue with the 2nd call to fibonacci? Nothing looks suspicious.

assembly
mips
asked on Stack Overflow Apr 23, 2020 by Display name

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0