读取字符串并在MIPS中显示前5个字符



我正在尝试读取用户输入字符串并显示前5个字符。我能够获取并打印字符串返回,但我得到内存地址越界最有可能在move $a0,$t8行,因为我给lb $t8的分配是错误的。我做不到。

#data segment
.data
buffer: .space 20       #allocate space for 20 bytes=characters
#text segment
.text
.globl __start 
#program start
__start:
#get user input
li $v0,8
#load byte space
la $a0,buffer
#tell the system the max length
li $a1,20
move $t1,$a0
syscall
#display the input
li $v0,4
syscall
#print 5 first characters
li $t6,5
loop:   lb $t8,($t1)
li $v0,4
la $a0,buffer
move $a0,$t8
syscall 
add $t1,1

#1 less letter to print
sub $t6,1
#have we printed all 5
bne $t6,0,loop

t1没有第一个字符串的字节吗?

对于这个问题以外的所有帮助和/或任何一般提示,我们都很感激。

移动指令不可能导致内存越界异常。只有加载和存储指令才会导致这种情况。

您正在使用syscall #4来打印单个字节,因此syscall试图解引用$a0中提供的字节作为指针,并且作为不匹配,这将会出错。

lb $t8,($t1)
li $v0,4
la $a0,buffer # putting buffer address in $a0
move $a0,$t8  # overwriting the buffer address with byte value in $t8
syscall 

最新更新