0

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
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
suliman
  • 43
  • 8
  • Search for MIPS strcpy and you'll find lots of examples. C-style strings are copied byte by byte until the nul-character terminator has been copied. You need to reserve sufficient space for the target: try `.space 80` or similar (you're only reserving 1 byte with that `.asciiz ""`). – Erik Eidt Mar 15 '21 at 22:08

1 Answers1

1

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
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
ConnerWithAnE
  • 1,106
  • 10
  • 26
  • hey my friend. thank you for the effort of making this code but unfortunately I just found out that I need to make it using the persecute call and I will edit the question rn with extra info. if you can help me with I would really appreciate that! – suliman Mar 24 '21 at 16:41