0

我正在尝试分配一个动态数组并让它接受来自控制台的输入,但是一旦我开始在数组中输入一些数字,它就会说出现异常 7 错误。(坏数据地址)

这是我在运行使用 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

我知道参数传递有很多多余的移动命令,但这主要来自故障排除。据我所知,动态数组应该在运行 syscall 9 后将它们的基地址存储在 $v0 中,对吗?(一个月前刚开始学习 MIPS。)

这是 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

奇怪的是,这段代码非常适合我必须在程序前面分配的静态数组,但是动态数组似乎破坏了我的代码,我不知道是不是因为我没有传递正确的值到子程序,或者是因为子程序一开始就有缺陷。

为了更全面地了解 subprograms 参数传递结构,我已将我的整个程序代码上传到 Pastebin此处。任何见解将不胜感激!

4

1 回答 1

0

您的程序将动态分配的数组视为其容量(或您称其为长度)等于分配的字节数,即您保留在数组中的元素每个都是一个字节。
但是您没有将字节写入数组;你正在写单词,每个单词有 4 个字节。因此,当您提示用户输入数组长度时,您需要在分配之前将获得的数字乘以 4,因为您的数组所需的字节数是length * 4.

于 2015-03-02T06:50:55.440 回答