Home > Software design >  How does it know when string ends without a terminator? (Code below)
How does it know when string ends without a terminator? (Code below)

Time:09-18

I'm learning MIPS on MARS and I am confused as per the following code. Because when I load an inputted string into a reserved space, the code outputs normally, even without a terminator. Why is this? I thought every string needed a terminator so the input buffer knows when to stop. Is there one filled in automatically or ...? Thanks in advance. Code is:

# 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

CodePudding user response:

MARS documentation for syscalls:

... Service 8 — Follows semantics of UNIX fgets.  For specified length n, the input string from the user can be no longer than n-1.  If the input string is less than that, this syscall adds newline to end. In either case, this syscall pads with null byte. ...

So, in your case, any input string of 78 bytes or less gets both a newline and a null terminator.


The newline is a pain as we often don't want it.

On another note, the .space 81 will be zeros upon program load, so the after the first syscall you will see zero padded to the end, but a second to the same area will not necessarily (i.e. if input was shorter), so the null termination behavior of syscall#8 is useful, and necessary — particularly since the service does not return the length of the input!


Also, note that MARS has documentation available in a menu item:

   Help menu ↪ MIPS tab → Syscall subtab

There is some other interesting material/information at the Help menu as well.

  • Related