guest
guest

Reputation: 1746

MIPS How to save address on stack?

I have this code:

.data

    array: .word 13, 11, 5, 9, 0, -3
    size: .word 6

.text

Main:
    la $a0, array
    lw $a1, size
    jal PrintIntArray
    j Exit

# $a0 - array, $a1 - size
PrintIntArray:
addi $sp, $sp, -12
li $t0, 0
sw $t0, 0($sp) # i
sw $a0, 4($sp) # array
sw $a1, 8($sp) # size

li $a0, '['
li $v0, 11
syscall

lw $t1, 8($sp) # size
ble $t1, $0, EmptyArray
    PrintLoop:
        lw $t1, 8($sp) # size
        lw $t0, 0($sp) # i
        bge $t0, $t1, PrintLoopEnd
            lw $t0, 0($sp) # i
            lw $t2, 4($sp) # array
            add $t2, $t2, $t0

            lw $a0, 0($t2) # <====== RUNTIME EXCEPTION AT THIS LINE !!!
            li $v0, 1
            syscall

            li $a0, ','
            li $v0, 11
            syscall

            lw $t0, 0($sp) # i
            add $t0, $t0, 1
            sw $t0, 0($sp)
            j PrintLoop
    PrintLoopEnd:
EmptyArray:

li $a0, ']'
li $v0, 11
syscall

jr $ra

Exit:

The line marked by me produces the following run-time exception:

Error in util.asm line 37: Runtime exception at 0x00400060: fetch address not aligned on word boundary 0x10010001

What did I do wrong? I suppose I made some mistake in loading/storing the address.

Upvotes: 0

Views: 4445

Answers (3)

Heath Hunnicutt
Heath Hunnicutt

Reputation: 19467

Rather than increment i by 1, try the following

add $t0, $t0, 4

rather than

add $t0, $t0, 1

This will add the size, in bytes, of a 32-bit integer to your index. The MIPS requires that 4-byte values be stored to and loaded from addresses which are multiples of 4-bytes. (I.e., with the low-order two bits zero.)

Upvotes: 0

Variable Length Coder
Variable Length Coder

Reputation: 8116

You are trying to do an unaligned 32-bit load, which is not allowed on (generic) MIPS architectures. When i equals one, you're trying to load form address 0x10010000 (array) + 1 (i). Try multiplying t0 (i) by 4 before adding it to t2 (array)

Upvotes: 1

Lance Richardson
Lance Richardson

Reputation: 4610

You need to multiply i by the size of the array element, then add it to the base address of the array in order to compute the address of the ith element. Note that, if the element size is 4 bytes, this multiplication can be performed easily by a left shift of two bits.

Upvotes: 1

Related Questions