How to Display String array in MIPS

Naruto picture Naruto · Oct 6, 2012 · Viewed 15.4k times · Source

This is a very beginner program in MIPS programming in which I am trying to take input from user and display the input data on the screen. But when I run this program, I get "Memory out of bound error" and then program crashes when it tries to display the data. What is wrong in this code:

.data 

Array: .space 20

Promt: .asciiz "Enter a String:\n"
Line: .asciiz "\n"

.text

main:

la $a0,Promt
li $v0,4
syscall

la $a0,Array
li $a1,20
li $v0,8
syscall

la $t0,Array  # BASE ADDRESS OF ARRAY
li $t1,4

Loop:

lw $a0,0($t0)

add $t0,$t0,$t1

beq $a0,0, Exit

li $v0,4

syscall


j Loop

Exit:

li $v0,10
syscall

Regards

Answer

Jeff picture Jeff · Oct 8, 2012

Two issues:

1) In your loop, you're doing a syscall with $v0 == 4, which prints the string at address $a0. What's in $a0? It's actual string data, which isn't a valid address. You probably wanted $v0 == 11 instead, which prints an individual character; but that leads into the next problem:

2) You're loading four characters at a time. A word is 4 bytes, and you're using lw which means 'load word'. You can only print one character at a time with the syscall 11, and your loop will only exit if it happens to load a chunk of 4 characters that are all zero. You should be loading one character at a time instead. Use lb (load byte) instead of lw (load word), and use $t1 == 1 instead of $t1 == 4.