Rahul Krishnan
Rahul Krishnan

Reputation: 43

MIPS bad address/ Exception

The code is a recursive block for calculating the factorial of a number. I am getting an exception at PC (bad address in text). I am taking a look at the trace but am not sure where the problem really is, other than the fact that my PC is showing garbage values. I am attaching the code down below.

.data
    prompt: .asciiz "Enter the n"
.text
    main:
        #User I/O
        li $v0, 4
        la $a0, prompt
        syscall
        li $v0, 5
        syscall
        add $a0, $v0, $zero
        jal fact
        j finish
    fact:
        addi $sp, $sp, -8  #adding two elements (reserve space), since stacks start from higher mem address
        sw $ra, 0($sp)
        sw $a0, 4($sp)

        slti $t0, $a0, 1
        beq $t0, $zero, loop

        addi $sp, $sp, 8
        addi $v0, $zero, 1

        jr $ra

    loop:
        addi $a0, $a0, -1
        jal fact    #stores address of the lw instruction and goes to label-->fact

    lw $a0, 0($sp)
    lw $ra, 4($sp)
    addi $sp, $sp, 8 #deleting 2 elements

    mul $v0, $v0, $a0
    jr $ra #until main ra, recursively go through fact(n)=fact(n-1)*n

    finish:

Simulator Used : QtSpim

Any help is appreciated. Thanks! Also am attaching the PC and register values in case it helps. Register values at the time of the error

Upvotes: 2

Views: 4674

Answers (1)

Peter Cordes
Peter Cordes

Reputation: 363980

Single-step with your debugger to find out what went wrong when lw $ra, 4($sp), and what you actually loaded and jumped to with jr $ra. That instruction just jumps to whatever address in $ra, and is the most likely candidate for setting the PC to something bogus.

It looks like you save $ra to 0($sp), but restoring it from 4($sp), so you're swapping the arg and the return address.

Also, your main isn't saving its $ra on entry at all, so you won't be able to return from main. You run a jal before saving $ra, so the only save/restore is inside fact (whose definition is mixed in with main? Don't do that. Instead of jumping over the definition of another function, just put code to return from main or make an exit system call at the bottom of main.)

Also you might be crashing when you j finish, which will fall off the end of your program into non-instructions.

Upvotes: 3

Related Questions