I’m trying to simply sum up an array in assembly.
int main(){
int a[5] = {1, 2, 3, 4, 5};
int result;
_asm{
mov ecx, 5 ;set the counter for 5
mov eax, 0 ;zero eax
NXT: add eax, [esi*4+a] ;add array value
inc esi ;increase esi to read next value
LOOP NXT ;loop back to next
mov [result], eax ;mov eax into result
}
printf("result: %u",result);
Regardless of what the value of the arrays are, it always sums to 2.
I’m trying to run on a Mac.
I’m compiling using:
gcc -fasm-blocks -m32 -c sum.cpp
and linking with
gcc -arch i386 -g -o sum sum.o
I’ve tried various things, but I can’t seem to get it to sum the array.
It looks like you aren’t initialising
esito anything, so it contains some random value at the start of your loop.Also, since
aexists at a non-fixed location (it is a local variable, after all), you should load the address ofainto a register first:I suspect your inline assembler is doing the wrong thing with
[esi*4+a].