0

I have to write a function in assembly to complete the following c code.

int main(){ int hist[26]={0}; int i; charHistogram("This is a string", hist); for (i=0; i<26; i++ ) printf("%c:%d ", i+’a’, hist[i] ); printf("\n"); } return 0; } 

And this is the assembly code I wrote:

_charHistogram: push %ebp movl %esp,%ebp subl $0x10,%esp movl $0x0,-0x4(%ebp) movl $0x41,-0x8(%ebp) condFor1: movl -0x4(%ebp),%edx movl 0X8(%ebp),%eax cmp (%eax,%edx,1), $0 je exit condFor2: cmpl $0x5a,-0x8(%ebp) jg condFor1 if1: movl -0x8(%ebp), %ecx cmp (%eax,%edx,1), %ecx jne if2 subl $0x41,%ecx movl 0xc(%ebp), %ebx add $0x1, (%ebx,%ecx,4) add 0x20,%ecx inc %ecx inc %edx jmp condFor1 if2: add 0x20,%ecx cmp (%eax,%edx,2), %ecx jne condFor1 subl $0x41,ecx movl 0xc(%ebp), %ebx add $0x1, (%ebx,%ecx,4) add 0x20,%ecx inc %ecx inc %edx jmp condFor1 exit: leave ret 

Basically the function written in assembly has to count the number of occurences of a letter on a given string and store it at the int array hist. So I thought it could compare each char value to its ascii value starting at 65 to 90 and from 97 to 122. But when I begin to compile the assembly it keeps getting the error "operand size mismatch for 'cmp'" for the instruction cmp (%eax,%edx,1), $0. Can you help me out?

2
  • for readability, please indent the C source code. suggest 4 spaces after an opening brace '{' and un-indent before a closing brace '}' Commented May 3, 2015 at 19:17
  • I think the entry point needs to be declared .global so it can be called Commented May 3, 2015 at 19:18

1 Answer 1

3
cmp (%eax,%edx,1), $0 

You need to reverse the operands.

cmp $0, (%eax,%edx,1) 

Did you notice that you have programmed endless loops?
You setup a variable with movl $0x0,-0x4(%ebp) but you are forgetting to change its value throughout the code!

Since your input string is ASCIIZ shouldn't you compare with CL in stead of comparing with ECX?

Sign up to request clarification or add additional context in comments.

2 Comments

yeah you´re right. it worked. Yes i've already changed the loops, thanks for the heads up. Theres a problem if i change de %ecx to %cl the i can't get the position of the int array that i get using add $0x1, (%ebx,%ecx,4). i says %cl is not valid base/index
The advice given to change %ecx into %cl only pertains to both compare instructions! cmp (%eax,%edx,1), %cl and cmp (%eax,%edx,2), %cl All other uses of %ecx can savely remain.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.