Finding the Nth character in a string and printing it MIPS32 assembler

984 views Asked by At

Ok so i have a simple program where given an integer as input by the user,suppose its X,tries to find the character at X position in a string.Works fine, but there is a little bug.As its easy to see,string length is 26 so if user enters for example 0->a must be printed, and so it does.But if i enter a number bigger than 25(since 1st char is at position 0) no errors appear....For example if i enter 40 i get as a result character e...Can somebody help me? As.Here is my code:

.text           
.globl main
main:
    li $s3,26 #string length


    la $a0, str1    # Load and print string asking for integer
    li $v0, 4
    syscall  

    li $v0,5 
    syscall
    add $s0 ,$v0, $zero #integer now in $s0



    la $a1,str #address of string now is $a1
    addu $a1,$a1,$s0   # $a1 = &str[x].  assumes x is in $s0
    lbu $a0,($a1)      # read the character
    li $v0,11
    syscall            # and print it







     li $v0,10
    syscall     



.data
str: .asciiz "abcdefghijklmnopqrstuvwzyz"
str1: .asciiz "give an integer: "
1

There are 1 answers

0
Weather Vane On BEST ANSWER

The processor will read whatever memory location you tell it to read (bar access permission). The index of 40 has picked out an 'e' from the next string in memory at

str1: .asciiz "give an integer: "

Best thing is to check the range of the number that was input. Assembly language has none of the inbuilt safeguards that higher lever languages have - only memory access constraints, implemented in the hardware.

Edit: There are other inbuilt safeguards in the processor, but they are not "language" oriented. Processors may have a watchdog that requires regular kicking to make sure the program has not got stuck somewhere that the programmer did not intend. Divide by zero is another. But the processor's response is brutal, and does not help the program's flow of logic at all.

Generally, the only error handling your assembly program gets is that picked up by the asembler itself, and what you code into the program. So if you want an error for an out of range index - that's your job.

These are the basic reasons why higher level languages evolved.