【问题标题】:How does it know when string ends without a terminator? (Code below)它如何知道字符串何时结束而没有终止符? (代码如下)
【发布时间】:2021-09-08 11:09:15
【问题描述】:

我正在 MARS 上学习 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

【问题讨论】:

  • 显式长度字符串很好,只要您不尝试将它们传递给不需要长度的函数或系统调用(而是寻找终止符)。即采用隐式长度的 C 字符串。不幸的是,MARS 继承的传统读取字符串 SPIM 系统调用是愚蠢的,并且不返回读取的字节数。但读取文件 (fread) 调用确实做到了。

标签: assembly mips mars-simulator


【解决方案1】:

系统调用的 MARS 文档:

... 服务 8 — 遵循 UNIX fgets 的语义。对于指定长度n,用户输入的字符串不能超过n-1。如果输入字符串小于该值,则此系统调用将换行添加到结尾。 在任何一种情况下,这个系统调用都用空字节填充。 ...

因此,在您的情况下,任何 78 字节或更少字节的输入字符串都会同时获得换行符和空终止符。


换行很痛苦,因为我们通常不想要它。

另一方面,.space 81 在程序加载时将为零,因此在第一个系统调用之后,您将看到零填充到末尾,但同一区域的第二个则不一定(即,如果输入更短) ,因此 syscall#8 的空终止行为是有用且必要的——特别是因为服务不返回输入的长度!


另外,请注意 MARS 在菜单项中提供了文档:

   帮助菜单 ↪ MIPS 选项卡 → 系统调用子选项卡

“帮助”菜单中还有一些其他有趣的材料/信息。

【讨论】:

    猜你喜欢
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 2013-05-18
    • 1970-01-01
    • 2013-03-19
    • 2011-06-07
    相关资源
    最近更新 更多