I wrote the following assembly function callable from C to count the length of a null-terminated string. But for some reason, the count is always off by +1. I can’t figure out why. Any clue?
Thanks!!!
1 .text
2 .globl _len
3 _len:
4 pushl %ebp # set up stack frame
5 movl %esp, %ebp # save esp in ebp
6 movl 8(%ebp), %ecx # the beg of string
7 xor %eax, %eax # init length to 0
8
9 start:
10 xor %edx, %edx # char at this index
11 movb (%ecx), %dl #
12 inc %eax
13 inc %ecx
14
15 cmpb $0x0, %dl
16 jne start
17 end:
18
19 movl %ebp, %esp # restore esp
20 popl %ebp # restore ebp
21 ret
22 .end
23
You are counting the terminating zero char. Either start with -1 or increment after the comparison.