Search code examples
arraysdynamicmipsallocationqtspim

MIPS Dynamic Array Error


I'm trying to allocate a dynamic array and get it to accept input from the console, but once I start entering a few of the numbers into the array it says there is an Exception 7 error. (Bad Data Address)

Here is the code I use before running the subprogram which reads the numbers from the console using read_array:

la $a0, bIntro_p
li $v0, 4
syscall

li $a0, 0 #reset
li $a1, 0 #reset

li $v0, 5
syscall
move $t0, $v0 #moves length into $t0 for allocation, keeps length there

li $v0, 9 #allocation, sets base address into $v0
move $a0, $t0
syscall #base address is now in $v0
move $t1, $v0 #base now in $t1

move $a0, $t0 #length ($t0) goes into $a0 before reading
move $a1, $t1 #base address ($t1) goes into $a1 before reading

jal read_array

I know the argument passing has a lot of superfluous move commands, but thats mainly from troubleshooting. From what I've learned, dynamic arrays should store their base addresses in $v0 after running syscall 9 right? (Just started learning MIPS a month ago.)

Here is the subprogram for read_array:

read_array:
# Read words from the console, store them in
# the array until the array is full
li $t0, 0
li $t1, 0

move $t0, $a0 #length
move $t1, $a1 #base address
li $t9, 0 #makes sure count is reset before engaging
sw $t1, myBaseHolder #save the base address into the holder word

rWhile:

bge $t9, $t0, endR #branch to end if count > length

li $v0, 5 #call for an int from console
syscall

sw $v0, 0($t1) #saves the word from the console into the array

addiu $t9, $t9, 1 #count++
addiu $t1, $t1, 4 #increments the address
b rWhile

endR:

jr $ra

The weird part is that this code is working perfectly for the static array I have to allocate earlier in the program, but the dynamic array seems to break my code, and I can't tell if it's because I'm not passing the correct values to the subprogram or if it's because the subprogram is flawed to begin with.

For a more extensive look at the subprograms argument passing structures, I've uploaded my entire code for the program to Pastebin here. Any insight would be super appreciated!


Solution

  • Your program treats the dynamically allocated array as if its capacity (or length as you call it) is equal to the number of bytes allocated, i.e. as if the elements you're keeping in the array were one byte each.
    But you're not writing bytes to the array; you're writing words, which are 4 bytes each. So when you prompt the user for an array length you need to multiply the number you get by 4 before doing the allocation, since the number of bytes you need for your arrayt is length * 4.