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.
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.