0

I am tring to compare a character from a char pointer, i.e. a string, with another specified char, to find the first occurence of that char in the string. However, the char from the char pointer is returning wierd values, I am not sure how to do it.

This is my assembly code:

findChar:
    mov $0, %eax
start:
    cmp (%rdi), %esi
    je done
    add $1, %rdi
    inc %ebx
    jmp start
done:
    ret

I am calling the this function from C:

int findChar( char *str, char ch );

I tried returning the value of (%rdi) when it was supposed to match. When printing the return value as a char it is correct, however the integer value is something like 112410010, i.e. alot.

Thanks for any help

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • 1
    That is a 32-bit compare, and while that might be ok for `%esi` as that may be properly zero extended to 32-bits, the problem is that the memory access via `(%rdi)` is also 32-bits because of the size of `%esi`, so it is grabbing 4 characters at once from memory. Use `cmp (%rsi), %sil` instead for an 8-bit memory access and 8-bit compare. – Erik Eidt Apr 18 '23 at 03:41
  • 1
    Near duplicate of [How to compare a char in a string with another char in NASM x86\_64 Linux Assembly](https://stackoverflow.com/q/35927302) except that's Intel syntax (NASM), not AT&T. Same bug, though, using an operand-size other than byte compares multiple bytes as a wider integer. [How to traverse a string in assembly until I reach null? (strlen loop)](https://stackoverflow.com/q/60482733) shows working code, but use `%sil` instead of `$0` since you're implementing `rawmemchr` instead of `strlen`. – Peter Cordes Apr 18 '23 at 05:46

0 Answers0