Home > database >  Why does my string-print function print extra garbage / file contents after the C string I pass it?
Why does my string-print function print extra garbage / file contents after the C string I pass it?

Time:03-21

I decided to make a function that prints a string in the EAX register to the console, works from a part by displaying a message first, then something

Code (NASM) :

newLine equ 0xa

section .data
    msg db "Hello world!", newLine, 0

section .text
    global _start

_start:
    mov eax, msg
    call printf
    call exit

printf:
    push eax
    push ebx
    push ecx 
    push edx 

    mov ecx, eax
    call lenFind
    mov edx, eax
    mov eax, 4
    mov ebx, 1
    int 0x80

    pop edx
    pop ecx
    pop ebx
    pop eax 
    ret

lenFind:
    push edx
    mov edx, 0
    .find:
        cmp [eax edx], byte 0
        je .close
        inc edx
        jmp .find
    .close:
        pop edx
        ret

exit:
    mov eax, 1
    mov ebx, 0
    int 80h 

Output:

Hello world!
.shstrtab.text.data
                   �J�  

idk what it could be, but most likely the problem is that I'm using 32 bit registers

CodePudding user response:

Your lenFind does not return any result!
The length is calculated in the EDX register but you have restored that from the stack. However the calling program seems to expect the length to be in the EAX register:

lenFind:
    push edx
    mov edx, 0
    .find:
        cmp [eax edx], byte 0
        je .close
        inc edx
        jmp .find
    .close:
        MOV EAX, EDX   <<< Add this line
        pop edx
        ret
  • Related