please could you help me? I have to rewrite strlen function from C to Assembly language. Iput string is ended with "0h". Output length is without char "0". Input is alway ended with "0h" I have something like that but it doesnt work:
[segment .data use32]
; ******************************************************************
str: resb 50
str1: resb 50
str2: resb 50
aTmpWord: dw 0
aTmpDWord: dd 0
strlen:
push EBP
mov EBP, ESP
mov AL, 0h
mov EDI, dword [EBP + 8]
mov EBX, 0
vypocet_str:
cld
repne scasb
je koniec_str
inc EBX
mov EDI, [EDI + EBX]
jmp vypocet_str
koniec_str:
mov EAX, EBX
mov ESP, EBP
pop EBP
ret
;************
prologue
push dword [str]
call strlen
call WriteNewLine
call WriteInt32
epilogue
There are several mistakes in your code
1)
strlen
is officially declared assize_t strlen(const char *s);
. Argument is a pointer to a string. Withpush dword [str]
you don't pass a pointer, but the first 4 bytes of the string. Change it topush str
. NASM (unlike MASM) calculates then the address ofstr
.2) The
cdecl
calling conventions determines that arguments are passed on the stack and the caller must clear the stack. You correctly pushed the argument but don't clear the stack. Add aadd esp, 4
aftercall strlen
.3)
repne
needs an initialization ofECX
. This is the maximal count of the repetitions.4)
repne
is the instruction for a loop. You don't need an extra loop (jmp vypocet_str
). It repeats the following instruction while ECX>0 and the instruction don't tell an "equal" (zero flag set). So ECX can be used to determine the counts of the repne-run - with a little adjust.TL;DR: here is your homework in a beautiful form: