SOLVED: move command does not store things on the stack as I thought it did, instead I needed to use store word sw once I did that everything mostly worked
We are tasked with implementing a recursive function which has been given to us in the following psuedocode
main()
{ keyboard_input N;
sum = rec_add( N );
print sum;
}
rec_add( word n )
{ if (n==0) return 0;
return ( rec_add( n-1 ) + n );
}
I've written most of the program excluding the keyboard input(learning in class soon) but when I go to run the program I always error out on my BNE statement, and I am not sure why.
.data
.text
.globl main
main:
###########################
## your code starts here ##
###########################
addi $t0, $0, 3 #this is the starting nubmer
sub $sp, $sp, 4 #moves the stack pointer just to make sure to not overwrite anyone
move $sp, $t0 #put the starting number in the stack
jal rec #move to the recursion
addi $sp, $sp, 4
#########################
## your code ends here ##
#########################
## exit ##
addi $v0, $0, 10
syscall
## End main ##
###################################
## recursive function starts here ##
###################################
###########
#RECURSION#
###########
rec:
lw $t0, 0($sp) #Load value from the stack
#PROBLEM CODE IS HERE AS FAR AS I CAN TELL############################
bne $0, $t0, moveStack #if the value we just got isn't 0 we recurse
jr $ra #jump to the return address
################
#Recursive part#
################
moveStack:
sub $sp, $sp, 4 #Move stack down
move $sp, $ra #store return address in Stack
addi $t0, $t0, -1 #move the value down by one for next recursion
sub $sp, $sp, 4 #move down the stack
move $sp, $t0 #put the new number in the stack
jal rec #loop through recurision again
add $v0, $sp, $0 #get the current value from the stack
addi $sp, $sp, 4 #move up the stack
move $sp, $ra #get return address from the stack
addi $sp, $sp, 4 #move up
add $sp, $v0, $sp #add the older value with the new value into the stack and store it in the stack so that the next recursion is that + that(this is the plus n instruction
jr $ra
#############################
## your function ends here ##
#############################
I expect it to run and print out the sum of all the recursive calls. but when I run I get the error "Exception Occured at PC=0x00400070" followed by "Unaligned address in inst/data fetch: 0x00000003" This is running on the SPIM mips simulator on default settings. The Print statements have also been removed to save time on debugging as they were written by the professor.
User contributions licensed under CC BY-SA 3.0