MIPS,函数调用进入无限循环

时间:2013-11-29 18:13:37

标签: mips infinite-loop infinite

C代码

int GCD(int m, int n) 
{ //Call MACRO PRINTARGS as the first line of code in GCD 
 //PRINTARGS($a0, $a1) 

 int result = 0; 

 // Base Case: 
if(m == n) 
 result = m; 
else if (m > n) 
// Recursive Case: 
 result = GCD(m-n, n); 
else 
// Recursive Case: 
 result = GCD(m, n-m); 

 //Call MACRO PRINTARGS as the last line of code in GCD before jr $ra 
//PRINTARGS($a0, $a1) 
return result; 
}

GCD: 如果第一个参数大于第二个参数,我的函数将进入无限循环 (除了m = 2,n = 1的情况)

$a2 is m
$a3 is n
$v1 is where i store the result 

最大公分母(GCD)是将两者分开的最大正整数 没有余数的数字。 (PRINTARGS只是我编写的一个函数,用于在每次运行循环时打印m和n的值)

GCD:
PRINTARGS($a2,$a3)
addi $sp $sp,-4
sw $ra 0($sp)

lb $a0,newline
li $v0,11
syscall     #print new line
li $v1,0    # result = 0 result = v1
#base case
bne $a2,$a3,else2   #if m!=n, go to else2
move $v1,$a2        #move value m to v1
j GCD_DONE          #jump to GCD_DONE
#Recursive Case: else if (m > n), result = GCD(m-n, n); 
else2:
blt $a2,$a3,else3   #if m >n jump to else 3
sub $a2,$a2,$a3 #m-n
jal GCD
else3:
#Recursive Case: result = GCD(m, n-m); 
sub $a3,$a3,$a2 #n-m
jal GCD
PRINTARGS($a2,$a3)
GCD_DONE:
addi $sp $sp,4
lw $ra 0($sp)
jr $ra

1 个答案:

答案 0 :(得分:0)

两件事:

首先,在else2子句中,函数在递归调用后继续执行else3。改为:

else2:
    blt $a2,$a3,else3   #if m >n jump to else 3
    sub $a2,$a2,$a3 #m-n
    jal GCD
    j GCD_DONE

此外,您应该在从堆栈中恢复后递增$sp