首页 > 解决方案 > MIPS:将字符串输入存储到内存中

问题描述

这是 MIPS 程序要求输入字符串然后打印出来的最小工作示例:

.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:

我收到一个错误,即Error in line 24: Runtime exception at 0x00400044: address out of range 0x00000008. (第 24 行,作为参考,方法syscall之前的最后一个readString。)我不允许修改上面的代码_readString:;换句话说,我只是为_readString函数编写和实现代码。我相信该错误与内存分配有关,尽管我不确定具体问题是什么。任何帮助表示赞赏。谢谢。

标签: mipsheap-memory

解决方案


根据迈克尔的建议,第 18 行的命令是错误的。而不是sw $v0, 0($s3)它应该改为阅读sw $a0, 0($s3)。提供的代码中有错误。


推荐阅读