0
votes

Hello I am new to MIPS assembly language and Im trying to write the equivalent of B[8]=A[i-j] where variables f, g, h, i, and j are assigned to registers $s0, $s1, $s2, $s3, and $s4, respectively. I assume that the base address of the arrays A and B are in registers $s6 and $s7, respectively.

My code

# Gets A[i-j]
sub $t1, $s3, $s4 
sll $t1, $t1, 2
add $t1, $s6, $t1

lw $t0, 0($t1)

# Set B[8] equal to above
addi $t2, $s0, 8
sll $t2, $t2, 2
add $t2, $s7, $t2

lw $t2, 0($t2)
sw $t2, 0($t0)

but this throws a runtime exception at 0x0040000c: address out of range 0x00000000, any advice?

1
Fire up the debugger and answer the following: which instruction is at address 0x0040000c? What do the registers contain at that time, and how could they have come to contain that? - moonshadow
Have you verified that $s6 actually contains a valid address? And what values do you have in $s3 and $s4? - Michael

1 Answers

2
votes
# Gets A[i-j]
sub $t1, $s3, $s4 
sll $t1, $t1, 2
add $t1, $s6, $t1

lw $t0, 0($t1)

# Set B[8] equal to above
addi $t2, $s0, 8              #this actually computes something like &B[f+8], not &B[8]
sll $t2, $t2, 2
add $t2, $s7, $t2

lw $t2, 0($t2)                #this loads the value B[f+8]
sw $t2, 0($t0)                #this stores B[f+8] to *(int *)A[i-j], which is probably not an address.

If you want your code to match your description, you have to:

# Gets A[i-j]
sub $t1, $s3, $s4 
sll $t1, $t1, 2
add $t1, $s6, $t1

lw $t0, 0($t1)

# Set B[8] equal to above
addi $t2, $zero, 8
sll $t2, $t2, 2
add $t2, $s7, $t2

##deleted##lw $t2, 0($t2) no need to load B[8] if you just want to write to it
sw $t0, 0($t2) #this stores A[i-j] to &B[8]