How to Display String array in MIPS

15.7k views Asked by At

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

2

There are 2 answers

0
Jeff On

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.

0
progfan On

as Jeff pointed out, you seem to have loaded an inappropriate value into $a0. The following is a modification of your program. I have made two simple changes to your program.

 .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    
    lw $a0,0($t0) #***MOVED THIS OUT***     
    Loop:
        add $t0,$t0,$t1         
            beq $a0,0, Exit         
            la $a0, Array       
            li $v0,4        
            syscall         

            li $a0, 0  #****ADDED THIS LINE****         
            j Loop

    Exit:
        li $v0,10   
            syscall