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

2
  • 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. Commented Apr 18, 2023 at 3:41
  • 1
    Near duplicate of How to compare a char in a string with another char in NASM x86_64 Linux Assembly 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) shows working code, but use %sil instead of $0 since you're implementing rawmemchr instead of strlen. Commented Apr 18, 2023 at 5:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.