【问题标题】:Strange bug in MIPS codeMIPS 代码中的奇怪错误
【发布时间】:2014-03-07 20:35:04
【问题描述】:

我正在为用户编写一个程序来输入一系列数字,并计算最小值、最大值和中位数。现在,我只是想收集数字并将它们回显以确保我得到它们。问题来了:

我输入这样的数字: 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

【问题讨论】:

  • 对我根本不起作用。单次进入后永不终止。
  • 对不起,我要补充一点,您必须输入 9999 才能退出循环

标签: arrays debugging architecture mips system-calls


【解决方案1】:

这里有一些问题。

首先,您的所有函数都缺少终止 jr $ra

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

最重要的是你的intArray 指令。您使用了.word 4000 我猜是分配一个整数数组,但您已经为 1 个字分配了空间,其值为4000

要分配一个 1000 个整数的数组,您可以使用 .space 4000 或同样的 .word 0:1000

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

【讨论】:

  • 非常感谢,帮了大忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
  • 2014-04-09
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多