Assembly x86 String Concatenation

Asked

Viewed 423 times

1

I have to implement a function that concatenates a String3 pointed by ptr3 to the strings pointed by ptr1 and ptr2. I do the main() in C, and functions in Assembly x86. When executing, the output is 123 whereas it should be 123456.

My code is as follows, divided by files:

MAIN. C

//variáveis globais

char string1[] = "123";

char string2[] = "456";

char string3[] = "";

char* string1Ptr = string1;

char* string2Ptr = string2;

char* string3Ptr = string3;

int main(){

printf("String1: %s\n", string1);

printf("String2: %s\n", string2);

str_cat();

printf("String3: %s\n", string3);

return 0;
}

ASSEMBLY FUNCTIONS

.section .data

    .global string1Ptr

    .global string2Ptr

    .global string3Ptr


.section .text

    .global str_cat

str_cat:

    #prologue
    pushl %ebp                  #save previous stack frame pointer
    movl %esp, %ebp             #the stack frame pointer for sum function

    movl string1Ptr, %ebx   
    movl string2Ptr, %ecx
    movl string3Ptr, %eax       #String final

    str_loop1:
        cmpl $0, (%ebx)         #verifica se está no final da string
        jz end                  #jump se zero

        movb (%ebx), %dl        #guardar a letra        
        movb %dl, (%eax)

        incl %ebx
        incl %eax

        jmp str_loop1

    str_loop2:
        cmpl $0, (%ecx)
        jz end

        movb (%ecx), %dl
        movb %dl, (%eax)

        incl %ecx
        incl %eax

        jmp str_loop2


    end:
        #epilogue
        movl %ebp, %esp         #restore the previous satck pointer("clear" the stack)
        popl %ebp               #restore the previous stack frame pointer
        ret

What could be wrong?

  • 1

    What is the specific question ? The code in C did not reserve space in string3 for the result of concatenation, it should therefore be char string3[7]. And the code in Assembly did not put the terminator 0 in string3, as well as the end of the 1 loop is for the end not for the 2 loop

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.