MIPS: store string input into memory

0

Here is the minimum working example for a MIPS program to ask for a string input and then print it out:

.data
    enterString:    .asciiz "Please enter a string: "
    theString1: .asciiz "The string is"
    buffer: .space  100
.text
    # Allocate memory for an array of strings
    addi $v0, $zero, 9      # Syscall 9: Allocate memory
    addi  $a0, $zero, 4     # number of bytes = 4 (one word)
    syscall                   # Allocate memeory
    add  $s1, $zero, $v0         # $s1 is the address of the array of strings
    add  $s3, $zero, $s1         # $s3 is the temporary address of the array of strings
    #Ask user for input
    add  $v0, $zero, 4      # Syscall 4: Print string
    la   $a0, enterString      # Set the string to print to enterString
    syscall                   # Print "Please enter..."
   jal  _readString           # Call _readString function
   #Store it in memory
    sw   $v0, 0($s3)            # Store the address of a string into the array of strings
    add  $s3, $zero, $s1         # $s3 is the temporary address of the array of strings
    addi $v0, $zero, 4      # Syscall 4: Print string
    la   $a0, theString1       # Set the string to print to theString1
    syscall                   # Print "The string..."
    lw   $a0, 0($s3)            # Set the address by loading the address from the array of string
    syscall                   # Print the string
    j done
#Readstring: read the string, store it in memory. NOT ALLOWED TO CHANGE ANY OF THE ABOVE!!!!!!!!!
_readString:
    addi $v0, $zero, 8 #Syscall 8: Read string
    la $a0, buffer #load byte space into address
    addi $a1, $zero, 20 # allot the byte space for string
    syscall
    jr   $ra
done:

I am getting an error, namely Error in line 24: Runtime exception at 0x00400044: address out of range 0x00000008. (Line 24, is, for reference, the final syscall before the readString method.) I am not allowed to modify the code above _readString:; in other words, I am only to write and implement the code for the _readString function. I believe the error is linked to memory allocation, although I am not sure exactly what is the specific issue. Any help is appreciated. Thanks.

mips
heap-memory
asked on Stack Overflow Jun 8, 2018 by Hossmeister • edited Jun 9, 2018 by Hossmeister

1 Answer

0

By Michael's suggestion, the command on line 18 is wrong. Instead of sw $v0, 0($s3) it should read instead sw $a0, 0($s3). There was a mistake in the provided code.

answered on Stack Overflow Jun 9, 2018 by Hossmeister

User contributions licensed under CC BY-SA 3.0