Reputation: 580
so I am very new (extremely new) to assembly programming and am trying to write a function that can calculate the length of a string.
I feel I have some issue with clearing out values in registers, or with the incrementation of the pointer, because the value that is getting returned is always "4571 + length" for me.
Basically, if I have string length 0, I get 4571 as the return value. If I have string length 6, I get 4577 as the return value, etc.
Here's my code, any help will be appreciated:
.globl my_strlen
my_strlen:
pushq %rbp
movq %rsp, %rbp
pushq %r12
pushq %r13
movq $0, %rax
cmp $0, (%rdi)
jne my_strlen_loop
ret
my_strlen_loop:
inc %rax
inc %rdi
cmp $0, (%rdi)
jne my_strlen_loop
popq %r13
popq %r12
popq %rbp
ret
Upvotes: 1
Views: 510
Reputation: 12457
There are two problems with this code.
First, the cmp
instructions don’t specify a size, and neither operand is a register, so it's ambiguous. For most instructions (like mov $0, (%rdi)
), GAS would refuse to assemble it, but cmp
for some reason assembles to cmpl
, comparing a dword. Change the mnemonic to cmpb
explicitly.
Second, before the first ret, it doesn’t pop the registers that were pushed. It would be better to jump to the end (and have a single ret).
Upvotes: 4