0

我正在尝试计算用户给出的字符串的长度。每次我尝试运行代码时,我都会收到消息“PC=(某个地址)发生异常,然后是消息:”数据/堆栈读取中的错误地址:(另一个地址)。我知道它与堆栈有关,但我无法找出问题所在。MIPS 中的代码是 bello,我使用的是 QtSpim。您的帮助将不胜感激。

sentence:   .space 6
Prompt: .asciiz "Enter the sentence. Max 6 characters, plus a terminator  .\n"  

        .text       # Start of code section
main:               # The prompt is displayed.

    li $v0, 4        # system call code for printing string = 4
    la $a0, Prompt  # load address of string to be printed into $a0
    syscall         # call operating system to perform operation;
                    # $v0 specifies the system function called;
                    # syscall takes $v0 (and opt arguments)

##read the string, plus a terminator, into the sentence
    la      $t0,    sentence
    li      $t0,    6
    li      $v0,    8

    add $v0, $zero, $zero   #initialize length to zero
loop:
    lbu $s0, 0($t0)      #load one character of string
    addi $t0,$t0,1          #point to next character
    addi $v0,$v0,1          #increment length by 1
    bne $s0,$zero, loop     #repeat if not null yet
end_loop:
    addi $v0, $v0, -1       #don't count the null terminator

    li $v0, 4               #display the actual length
    syscall

exit: #exit the program 
    li $v0, 10
    syscall
4

1 回答 1

1
##read the string, plus a terminator, into the sentence
    la      $t0,    sentence
    li      $t0,    6

在这里,您正在加载sentenceinto的地址$t0,然后立即$t0用 value覆盖6。这可能是异常的根本原因,因为下面lbu将尝试从地址 0x00000006 读取。我建议你删除li.

   li      $v0,    8

    add $v0, $zero, $zero   #initialize length to zero

li是没有意义的,因为您$v0在下一行设置为零,因此li也可以将其删除。

sentence:           .space 6
Prompt:     .asciiz "Enter the sentence. Max 6 characters, plus a terminator  .\n" 

您说用户最多可以输入 6 个字符。但是您只为 6 个字节分配空间,这意味着如果用户实际输入 6 个字符,则 NULL 终止符将不适合。

于 2013-04-25T09:52:16.070 回答