MIPS 运行时错误“第 31 行:运行时异常位于 0x00400038:地址超出范围 0x7fbffffc Go:执行因错误而终止。”

问题描述 投票:0回答:1

我收到错误“第 31 行:运行时异常位于 0x00400038:地址超出范围 0x7fbffffc”

Go:执行因错误而终止。”每当我输入 2 时,当我输入 3 时,它会输出 3,当我输入 4 时,它会输出 4 而不是 8

代码应该做的事情

int Myfun (int N)
{
 if (N>3) return ( Myfun(N-2) + 2N );
 else return 0
}

我的代码是

          .data
input: .asciiz "Input: "
    .text
    .globl main
main:
    # Prompt user for input
    li $v0, 4
    la $a0, input
    syscall

    # Get user input
    li $v0, 5
    syscall
    move $a0, $v0

    # Call Myfun(N)
    jal Myfun

    # Print the result
    li $v0, 1
    syscall

    # Exit
    li $v0, 10
    syscall

Myfun:
    addi $sp, $sp, -8       # Reserve stack space for 2 items
    sw $ra, 4($sp)          # Save the return address
    sw $a0, 0($sp)          # Save the current value of N
    slti $t0, $a0, 3        # Test if N is less than 3
    beq $t0, $zero, Base_case     # If N < 3, jump to base_case
    addi $a0, $a0, -2       # Prepare the argument for the recursive 
    jal Myfun               # Recursive call
    lw $a0, 0($sp)          # After returning, load the original N
    add $t1, $a0, $a0     # Calculate 2N
    add $v0, $v0, $t1       # Add 2N to the result of the recursive 
    j Exit                  # Return from the function

Base_case:
    li $v0, 0         # Set the return value to 0 for the base case
    j Exit

Exit:
    lw $a0, 0($sp)
    lw $ra, 4($sp)          # Restore the return address
    addi $sp, $sp, 8        # Clean up the stack
    jr $ra                  # Return from the function
mips mips32
1个回答
0
投票

您有两个简单的问题,可以通过调试来识别。

首先,在

main
中,您将打印
$a0
而不是函数的返回值(位于
$v0
中)。因此,在
main
之后的
jal Myfun
中,您需要将
$v0
(返回值)移至
$a0
,以便系统调用 #1 打印整数。

其次,在

Myfun
中,您颠倒了 if 语句条件,以便在给定小于 3 的输入时函数不会收敛 - 经典的堆栈溢出。

您已编写以下代码:

int Myfun (int N)
{
 if (N<3) return ( Myfun(N-2) + 2*N );
 else return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.