CHAPTER 15. SIMPLE C-STRINGS PROCESSING CHAPTER 15. SIMPLE C-STRINGS PROCESSING
Chapter 15
Simple C-strings processing
15.1 strlen()
Let’s talk about loops one more time. Often, thestrlen()function^1 is implemented using awhile()statement. Here is
how it is done in the MSVC standard libraries:
int my_strlen (const char str)
{
const char eos = str;
while( *eos++ ) ;
return( eos - str - 1 );
}
int main()
{
// test
return my_strlen("hello!");
};
15.1.1 x86
Non-optimizing MSVC
Let’s compile:
_eos$ = -4 ; size = 4
_str$ = 8 ; size = 4
_strlen PROC
push ebp
mov ebp, esp
push ecx
mov eax, DWORD PTR _str$[ebp] ; place pointer to string from "str"
mov DWORD PTR eos$[ebp], eax ; place it to local variable "eos"
$LN2@strlen:
mov ecx, DWORD PTR _eos$[ebp] ; ECX=eos
; take 8-bit byte from address in ECX and place it as 32-bit value to EDX with sign extension
movsx edx, BYTE PTR [ecx]
mov eax, DWORD PTR _eos$[ebp] ; EAX=eos
add eax, 1 ; increment EAX
mov DWORD PTR eos$[ebp], eax ; place EAX back to "eos"
test edx, edx ; EDX is zero?
je SHORT $LN1@strlen ; yes, then finish loop
jmp SHORT $LN2@strlen ; continue loop
$LN1@strlen:
(^1) counting the characters in a string in the C language