MIPS fetch address not aligned on word boundary, used .align 4, still no go

The problem with the code is, that you’re not using the address where the size is stored but the size itself:

Here you load the address into A0 and the size (7) into A1:

        la  $a0,array   
        lw  $a1,size    #a1 = size of array

Here you load the first word stored at your array (that will load a 10). This is not what you’ve intended.

        lw $s0,0($a0)   #copy arg1 = address array
        addi $s1,$zero,7

Here you load the first word stored at location 0x000007. (your size). This is probably also not intended and will cause an exception because the address is not aligned:

        lw $s1,0($a1)   #copy arg2 = size of array

and so on.

It seems to me, that you have a misunderstanding what the LW instruction does. It reads a memory location into a register. What you want in the prolog of your loop is to make copies of a register.

To do so you can use the move pseudo instruction if your assembler supports it. Otherwise use the OR instruction to copy registers like this:

COUNT:
            or    $s0, $a0, $a0   #copy arg1 = address array
            addi  $s1, $zero,7
            or    $s1, $a1, $a1   #copy arg2 = size of array
            or    $s2, $a2, $a2   #copy arg3 = search key (n)
            addi  $s2, $zero,30
            COUNTLOOP:

            ...

for a complete example of a linear search loop try this (untested and expects that the assembler cares about the delay slots)

main:

            la  $a0,array            # $a0 = address of array
            lw  $a1,size             # $a1  = size of array
            lw  $a2,search           # $a2 = search key


            beq $a1, $zero, NOTFOUND # handle the size==0 case..
            or  $v0, $zero, $zero    # init counter to zero

LOOP:
            lw  $s0, 0($a0)          # load element
            beq $s0, $a2, FOUND      # branch if key found:

            addiu $a0, $a0, 4        # increment array pointer
            addiu $v0, $v0, 1        # increment loop counter
            bne   $v0, $a1, LOOP     # repeat until we've processed the array.

NOTFOUND:
            # --------------------------------------
            # if you reach this, key does not exist:
            # --------------------------------------
            li  $v0, -1              # load a -1 to signal key not found.
            jr  $lr                  # return to caller

FOUND:
            # -----------------------------------------
            # v0 now contains the position of the key.
            # -----------------------------------------
            jr  $lr

Leave a Comment