MIPS32字符串字符出现次数统计代码异常,请求调试
Let's walk through the bugs in your code that are causing the wrong (and huge) output value—there are a couple of critical issues to fix:
1. Wrong Loop Termination Condition
Your code uses a fixed loop limit of 100 (from $s1 = 100), but the string read by syscall 8 is null-terminated (ends with a \0 byte). If the user enters a string shorter than 100 characters, your loop will keep reading uninitialized garbage data from the remaining space in string, which leads to counting random bytes as matches—hence the huge number you're seeing.
Fix: Instead of looping 100 times, stop the loop as soon as you hit the null terminator (\0, ASCII value 0) of the string. You can adjust your loop logic to check the current character before processing, or add a null check before continuing.
2. Incorrect Print System Call Setup
In your print block, you made two key mistakes that break the output:
- You first load the count value into
$v0, but immediately overwrite it withli $v0, 1(the syscall number for printing integers). - MIPS's
syscall 1expects the integer to print to be in the$a0register, not$v0.
Fix: Move your count value from $t4 to $a0 before setting $v0 to 1.
Fixed Full Code
Here's the corrected version with comments highlighting changes:
.data string: .space 100 # Allocate space for string .text main: la $a0, string # Load string buffer address li $a1, 100 # Maximum input length li $v0, 8 # Syscall for reading string syscall la $s0, string # $s0 = base address of the string li $v0, 12 # Syscall for reading single character syscall move $s2, $v0 # $s2 = target character to count li $t4, 0 # Initialize count to 0 li $t0, 0 # Initialize index to 0 loop: add $t1, $s0, $t0 # Calculate address of string[$t0] lb $t2, 0($t1) # Load byte from string at index $t0 beq $t2, $zero, print # Exit loop if we hit null terminator (\0) bne $t2, $s2, skip # Skip count increment if no match add $t4, $t4, 1 # Increment count if character matches skip: add $t0, $t0, 1 # Increment index j loop # Return to loop start print: move $a0, $t4 # Move count value to $a0 (required for syscall 1) li $v0, 1 # Syscall for printing integer syscall li $v0, 10 # Syscall for program exit syscall
Additional Notes
- The fixed loop now stops at the null terminator, so it only processes the actual input string, not garbage data.
- The print logic correctly passes the count to
$a0before triggering the integer print syscall. - If you notice issues with leftover newline characters after reading the string, you could add a small loop to consume any remaining bytes in the input buffer, but this isn't necessary for basic functionality.
内容的提问来源于stack exchange,提问作者Little Stack

