Please write neatly and explain answer. Thanks in advance! The subroutine below
ID: 3868387 • Letter: P
Question
Please write neatly and explain answer. Thanks in advance!
The subroutine below is broken. It is supposed to be a string copy subroutine, but it never finishes. When it runs, the copied version of the string is just a terminating null. Fix it.;Copies null-terminated string to destination memory;r0 - pointer to string;r4 - pointer to destination strcpy: la r29, loop: pointer to loop label la r28, out;pointer to end addi r18, r0, 0;make copy of arg1 addi r19, r4, 0;make copy of arg2 loop: ld r20, (r18);load char from string St r20, (r19);store the character addi r18, r!8, 4;increment source pointer brzr r28, r20;was char 0?, if so get out br r29;loop and do it again out: br r30;branch back to callerExplanation / Answer
The corrected code is given below
strcpy: la r29, loop
la r28, out
addi r18, r0, 0
addi r19, r4, 0
loop: ld r20, (r18)
st r20, (r19)
addi r18, r18, 1
addi r19, r19, 1
brzr r28, r20
br r29
out: br r30
In the original code, the source pointer (r18) was incremented by 4 , where as it should be incremented by just 1 since each character takes 1 byte only. Because of this the pointer would sometimes skip the null terminator 0. Also the other bug is the the destination pointer(r19) is never incremented. So each time a character is copied, its copied into the 1st location itself and the last character copied is the null terminator.
So in order to fix the code, we need to increment both source(r18) and destination (r19) pointers by 1 and the loop terminates when null terminator is encountered. The 2 lines of correction are (shown above in the code)
addi r18, r18, 1
addi r19, r19, 1
Hope it helped. If so, please do rate the answer. Thank you.