0

The C main code:

#include <stdio.h>

int add1 (int *a, int n);

int main (void)
{
    int a[] = {1, 2, 3, 4, 5};

    printf("%d\n", add1(a, 5));

    return 0;
}

The assembly code of the function containg the commented C version:

/*
int add1 (int *a, int n) 
{
  int i;
  int s = 0;
  for (i=0; i<n; i++) s += *a++;
  return s;
}
returns the sum of the array elements
*/

.text

.globl add1
add1:
    pushl   %ebp        
    movl    %esp, %ebp  
    pushl   %ebx        
    pushl   %esi        

    movl    $0, %ebx    

    movl    $0, %esi    
L1:
    cmpl    12(%ebp), %esi  
    jge     out  
    addl    8(%ebp), %ebx
    addl    $4, 8(%ebp)
    incl    %esi
    jmp     L1
out:
    movl    %ebx, %eax
    popl    %esi
    popl    %ebx
    movl    %ebp, %esp
    popl    %ebp
    ret

Focus here

addl 8(%ebp), %ebx

addl $4, 8(%ebp)

Which should add the element of the array to ebx then move to the next element I suppose, but it doesn't. I'm not even getting memory values, I'm getting negative ones.

In fact pretty confused about all the array going to the stack or only the address of the first element. And by that, how to correctly add his initial value and move to the others.

What am I missing here?

1 Answer 1

2

8(%ebp) holds the address of the current element, so what you're doing is effectively s += a++; instead of s += *a++;.

You should be able to fix that with something like:

movl    8(%ebp), eax     /* eax = a   */
addl    (%eax), %ebx     /* ebx += *a */
addl    $4, 8(%ebp)      /* a++       */

Although it would probably be more efficient to move 8(%ebp) into a free register ( like %edi) before the loop, and then do addl (%edi),ebx / addl $4,%edi inside the loop.

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

1 Comment

Thank you @Michael, that did it. The 'more efficient' part was correct too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.