Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Translate the following C++ code into MIPS #/* strdup2.c - C code for strdup2 fu

ID: 3814838 • Letter: T

Question

Translate the following C++ code into MIPS


#/* strdup2.c - C code for strdup2 function:
#
# char * strdup2(char *str1, char *str2)
#
# strdup2 takes two strings, allocates new space big enough to hold
# of them concatenated (str1 followed by str2), then copies each
# string to the new space and returns a pointer to the result.
#
# strdup2 assumes neither str1 no str2 is NULL AND that malloc
# returns a valid pointer.
#
#*/
#char * strdup2 (char * str1, char * str2) {
# // get the lengths of each string
# int len1 = strlen(str1);
# int len2 = strlen(str2);
# // allocate space for the new concatenated string
# char *new = malloc(len1+len2+1);
#
# // copy each to the new area
# strcpy(new,str1);
# strcpy(new+len1,str2);
#
# // return the new string
# return(new);
#}

Explanation / Answer

Firstly, the function given to be converted into the respective MIPS required some changes as the

1. *new -> new is an keyword using it is not good practice, so changing to newalloc.

2. Adding an type cast from (void *) to (char *), so the code is as below:

#include<string.h>
#include<malloc.h>

char * strdup2 (char * str1, char * str2) {
// get the lengths of each string
int len1 = strlen(str1);
int len2 = strlen(str2);
// allocate space for the new concatenated string
char *newalloc = (char *)malloc(len1+len2+1);

// copy each to the new area
strcpy(newalloc,str1);
strcpy(newalloc+len1,str2);

// return the new string
return(newalloc);
}

Now converting the code to MIPS code would be as below:

$LFB0 = .
strdup2(char*, char*):
addiu $sp,$sp,-48
sw $31,44($sp)
sw $fp,40($sp)
move $fp,$sp
lui $28,%hi(__gnu_local_gp)
addiu $28,$28,%lo(__gnu_local_gp)
sw $4,48($fp)
sw $5,52($fp)
lw $4,48($fp)
lw $2,%call16(strlen)($28)
move $25,$2
1: jalr $25
nop

lw $28,16($fp)
sw $2,28($fp)
lw $4,52($fp)
lw $2,%call16(strlen)($28)
move $25,$2
1: jalr $25
nop

lw $28,16($fp)
sw $2,32($fp)
lw $3,28($fp)
lw $2,32($fp)
addu $2,$3,$2
addiu $2,$2,1
move $4,$2
lw $2,%call16(malloc)($28)
move $25,$2
1: jalr $25
nop

lw $28,16($fp)
sw $2,36($fp)
lw $5,48($fp)
lw $4,36($fp)
lw $2,%call16(strcpy)($28)
move $25,$2
1: jalr $25
nop

lw $28,16($fp)
lw $2,28($fp)
lw $3,36($fp)
addu $2,$3,$2
lw $5,52($fp)
move $4,$2
lw $2,%call16(strcpy)($28)
move $25,$2
1: jalr $25
nop

lw $28,16($fp)
lw $2,36($fp)
move $sp,$fp
lw $31,44($sp)
lw $fp,40($sp)
addiu $sp,$sp,48
j $31
nop

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote