'How to increment %eax register and output in a c callable function?
#include <stdio.h>
extern int count(char *string, char c);
int main(void)
{
char s[100];
char c;
printf("Enter a string of characters:\n");
scanf("%s", s);
printf("Enter a character to count:\n");
scanf("%c", &c);
printf("\nThe number of %c's in the string %s is %d\n", c, s, count(s,
c));
return 0;
}
I'm trying to run this code that will count how many char c's are in the string s through an external function in the x86 assembly below, but when I debug it in gdb, it gives me 0 no matter what and when I set a breakpoint before at the count function, it just skips over it and completes the program returning 0. I've tried debugging this for a good amount of time but I just can't figure it out, so does anyone have any pointers or suggestions that could lead me in the right direction? I'm new to assembly so I'm not sure if any of the code below is correct or if anything is unnecessary. Any help is greatly appreciated thanks!
.globl count
.text
# first argument is string, second argument is character
count:
push %ebp #push old ebp to top of stack
movl %esp, %ebp #point ebp to same thing as esp, both pointing to old ebp
#saving live registers
push %esi
push %edi
push %ebx
#take values from stack
movl $0, %eax #set count(eax) to 0
movl 12(%ebp), %ecx #move letter to be counted to ecx
movl 8(%ebp), %esi #move string to edx
lettercheck:
cmpb (%esi), %cl #compare current letter to ecx(letter to be counted)
incl %esi #next letter
je inccount #if match inccount
cmpb $0 ,(%esi) #if no match and end of string
je end
jmp lettercheck #if not end of string and no match
inccount:
incl %eax #inc count of char
cmpb $0, (%esi) #check for end of string
jne lettercheck #if match and not EOS lettercheck
jmp end #else jmp end
end:
pop %ebx
pop %edi
pop %esi
movl %ebp, %esp
pop %ebp
ret
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
