assemblymipsstrcpymars-simulatormips64

how to copy string a string to another one in mips assemply language


I've been trying to copy a string to another but couldn't find a way to do it can anyone help with this? here is the question: Write a program which will copy a string S to T using procedure call. Assume the string is null terminated.

here is the code that someone made it in stacks overflow and as what my instructor told me it's good but it just need to be modified to procedure call

.data

str1: .asciiz "My Name is Suliman." # Store initial string
str2: .space 128            # Allocate memory space for the new string

.text

main:
la $s0, str1            # Load address of first character
la $s1, str2            # Load the address of second string

loop:
    lbu  $t2, 0($s0)        # Load the first byte of $s0 (str1) into $t2

sb   $t2, 0($s1)        # Save the value in $t2 at the same byte in $s1 (str2)

addi $s0, $s0, 1        # Increment both memory locations by 1 byte
addi $s1, $s1, 1
bne  $t2, $zero, loop   # Check if at the zero delimiter character, if so jump to 

j done
done:
li $v0, 4
la $a0, str2
syscall                 # Print the copied string to the console

li $v0, 10              # Program end syscall
syscall

Solution

  • I have some comments here as well to explain what I am doing, I kinda just went for 128 bytes to have some headroom and I also print out the copied string as well

    .data
    
        str1: .asciiz "My Name is Suliman." # Store initial string
        str2: .space 128            # Allocate memory space for the new string
    
    .text
    
    main:
        la $t0, str1            # Load address of first character
        la $t1, str2            # Load the address of second string
    
    loop:                      # do {
        lbu  $t2, 0($t0)        # Load the first byte of $t0 (str1) into $t2
    
        sb   $t2, 0($t1)        # Save the value in $t2 at the same byte in $t1 (str2)
    
        addi $t0, $t0, 1        # Increment both pointers by 1 byte
        addi $t1, $t1, 1
        bne  $t2, $zero, loop  # }while(c != 0)
    
    #    j done        # execution falls through to the next instruction by itself
    #done:
        li $v0, 4
        la $a0, str2
        syscall                 # Print the copied string to the console
    
        li $v0, 10              # Program end syscall
        syscall