0

我想計算一個用戶給出的字符串的長度。每次我嘗試運行代碼時,都會收到消息「PC發生異常=(某個地址),然後是消息:」數據/堆棧中的地址錯誤讀取:(另一個地址)。我知道它與堆棧有關,但我無法弄清楚問題所在。 MIPS中的代碼是bello,我正在使用QtSpim。您的幫助將非常感激。嘗試顯示用戶給定的字符串長度時遇到異常。 MIPS

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 

回答

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

在這裏,我們加載的sentence地址爲$t0,然後立即與值6覆蓋$t0。這可能是異常的根本原因,因爲以下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結束符不適用。

+0

當我試圖搭乘:li $ t0,6時,它顯示提示兩次。但是當我保留那條線時,提示只顯示一次。但是,在嘗試刪除兩條線時,我仍然沒有預期的結果。 – T4000 2013-04-25 10:34:40

+0

@ T4000:這是可以預料的,因爲你再次執行系統調用4(print_string)來結束你的代碼,並且仍然有'$ a0'指向'提示符'。你也沒有實際讀取用戶字符串的代碼。 – Michael 2013-04-25 11:18:55

相關問題