A Sample Program Using the Runtime Stack


The following program shows how to use the runtime stack by reversing a string. The memory addressing mode str( $t1 ) means Therefore, you can use this method to access each byte of the string str starting from $t1=0 till str($t1) == 0.

Reverse and Output a User-Supplied String
 # Reverse and output a user-supplied string
 #
 # $t0 --- character pushed or popped
 # $t1 --- index into string buffer str

         .data
 str:    .space  128             # character buffer 

         .text
         .globl  main

         # Input the string.
 main:   la      $a0, str        # address of buffer
         li      $a1, 128        # buffer length 
         li      $v0, 8          # service code -- read string
         syscall
        
         subu    $sp, $sp, 4     # push a null onto the stack
         sw      $0, ($sp)       # to signal its bottom
         li      $t1, 0          # index of first char in str buffer

         # Push each character onto the stack.
 pushl:  lbu     $t0, str($t1)   # get current char into
                                 # a full word
         beqz    $t0, stend      # null byte: end of string
        
            # push the full word
         sw      $t0, ($sp)      # holding the char
        
         addu    $t1, $t1, 1     # inc the index
         j       pushl           # loop

         # Pop chars from stack back into the buffer.
 stend:  li      $t1, 0          # index of first byte of str buffer 

 popl:   lw      $t0, ($sp)      # pop a char off the stack
         addu    $sp, $sp, 4
         beqz    $t0, done       # null means empty stack
        
         sb      $t0, str($t1)   # store at string[$t1]
         addu    $t1, $t1, 1     # inc the index
         j       popl            # loop
 
         # Print the reversed string.
 done:   la      $a0, str        # address of string
         li      $v0, 4          # service code -- print string
         syscall
         li      $v0, 10         # exit
         syscall
 
An Execution Example
   12345

   54321

Note that there is a blank line between the input and output. It is because according to the definition of the read_string service of syscall So the newline is part of input.




      Who would survive if Trump and Clinton both were stranded on a island?    
      — America