繁体   English   中英

MIPS代码中的奇怪错误

[英]Strange bug in MIPS code

我正在制作一个程序,供用户输入一定范围的数字,并计算最小值,最大值和中位数。 现在,我只是试图收集这些数字并回显它们,以确保我得到它们。 这是问题所在:

我输入这样的数字:1 2 3 4 5

当打印出数组时,我得到:15345

不管使用什么数字,数组中的第二个元素总是被最后一个元素替换。

这是我的mips代码,我知道它有点长,但这是我能做的最短的可行示例。

注意:您必须输入9999,程序才能退出循环。

.data 
welcomeString:  .asciiz "Please input one number at a time, and then press enter.\n"
intArray: .word 4000
size: .word 0

.text
main:
li $v0, 4
la $a0, welcomeString
syscall
la $a0, intArray
jal gather_numbers
la $a0, intArray
jal print_array

####################################################################################

gather_numbers:
addi $sp, $sp, -12
sw $a0, 0($sp)
sw $s0, 4($sp)
sw $s1, 8($sp)
sw $t1, 12($sp)

move $s0, $a0 #the address of the array
lw $s1, size # load the size
li $t1, 0 # so it enters the loop

start_gather_numbers: beq $t1, 9999, exit_gather_numbers
              li $v0, 5 # read the integer
              syscall
              sw $v0, 0($s0)
              move $t1, $v0 # put the value into t1 to be tested
              addi $s0, $s0, 4 #increment the address
              addi $s1, $s1, 1 # increment the size
              j start_gather_numbers
exit_gather_numbers:  addi $s1, $s1, -1 # fix the size
                  sw $s1, size # store the size
              lw $a0, 0($sp) # pop the stack
              lw $s0, 4($sp)
              lw $s1, 8($sp)
              lw $t1, 12($sp)
              addi $sp, $sp, 12

####################################################################################

####################################################################################

print_array:
addi $sp, $sp, -16
sw $a0, 0($sp)
sw $s0, 4($sp)
sw $s1, 8($sp)
sw $t0, 12($sp)
sw $t1, 16($sp)

move $s0, $a0 # the address of the array
lw $s1, size # load the size of the array
li $t0, 0 # i = 0

start_print_array: bge $t0, $s1, exit_print_array
                   lw $t1, 0($s0) # load the int to print
                   li $v0, 1 # print the integer
           move $a0, $t1
           syscall
           addi $s0, $s0, 4
           addi $t0, $t0, 1
           j start_print_array
exit_print_array:  lw $a0, 0($sp)
           lw $s0, 4($sp)
           lw $s1, 8($sp)
           lw $t0, 12($sp)
           lw $t1, 16($sp)
           addi $sp, $sp, 16

这里有些错误。

首先,您的所有功能都缺少终止的jr $ra

另外,您的堆栈操作错误。 您始终分配的字节数要少于您使用的4个字节。 如果要将5个单词放在堆栈上,则应将堆栈扩展20而不是16

最重要的是,这里是您的intArray指令。 您已经使用了.word 4000我想分配一个整数数组,但是您为1个单词分配了空间,值4000

要分配1000个整数的数组,可以使用.space 4000或相等的.word 0:1000

当我进行了这些更改时,您的程序开始按需运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM