You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MIPS MARS中读取字符串未加终止符仍可正常输出的原因是什么

MIPS MARS模拟器读字符串自动补终止符问题解答

核心结论

你观察到的现象是MARS模拟器syscall 8(读字符串系统调用)的固有设计,确实会自动填充\0作为字符串终止符,不需要手动添加。

MARS syscall 8 行为规则

当触发读字符串系统调用时,MARS会遵循以下逻辑处理输入:

  • 传入$a1的参数为输入缓冲区最大允许长度,系统最多仅读取$a1 - 1个用户输入的有效字符,预留最后1字节自动写入ASCII 0(即字符串终止符\0)
  • 若用户输入内容(含末尾回车符)长度小于$a1 - 1,系统会将回车符存入缓冲区后,紧跟写入\0
  • 若用户输入内容长度超过$a1 - 1,系统会自动截断前$a1 - 1个字符,末尾补\0

代码匹配说明

你当前测试代码中设置inputSize为80,所以系统最多读取79个输入字符,末尾自动补\0,后续调用syscall 4(打印字符串)时,会识别到终止符停止输出,因此可以正常工作。

提示:该自动补终止符的逻辑仅适用于MARS、SPIM这类教学类MIPS模拟器,工业级MIPS环境或裸机开发场景下的读接口可能无该默认逻辑,需手动处理字符串终止符。

测试代码

# Filename: mips3.asm
# Author: me
# Program to read a string from a user, and
# print that string back to the console.
.data
prompt:     .asciiz "Please enter a string: "
output:     .asciiz "\nYou typed the string: "
input:      .space 81       # Reserve 81 bytes in Data segment
inputSize:  .word 80        # Store value as 32 bit word on word boundary
                        # A word boundary is a 4 byte space on the
                        # input buffer's I/O bus.
# Word:
    # A Word is the number of bits that can be transferred
    # at one time on the data bus, and stored in a register
    # in mips a word is 32 bits, that is, 4 bytes.
    # Words are aways stored in consecutive bytes,
    # starting with an address that is divisible by 4

.text
# Input a string.
li $v0, 4
la $a0, prompt
syscall

# Read the string.
li $v0, 8           # Takes two arguments
la $a0, input       # arg1: Address of input buffer
lw $a1, inputSize   # arg2: Maximum number of characters to read
syscall

# Output the text
li $v0, 4
la $a0, output
syscall

# Print string
li $v0, 4
la $a0, input
syscall

# Exit program
li $v0, 10
syscall

内容的提问来源于stack exchange,提问作者John Connor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:27:03