0

This was the problem statement to be coded using GAS assembler.

Write an ALP program to find the largest number from a given array of numbers(stored contiguously in memory) and display the number.

I wrote this code:

.data

.text
.globl _start
_start:
  movl $5, -20(%ebp)
  movl $0, -16(%ebp)
  movl $1, -12(%ebp)
  movl $3, -8(%ebp)
  movl $4, -4(%ebp)
  movl $0, %ecx    # max value
  movl $5, %eax    # iterator
  loop:
    subl -1, %eax
    cmp $0, %eax
    # loop code here


terminate:
  movl $4, %eax
  movl $1, %ebx
  movl $1, %edx
  int $0x80
  movl $1, %eax
  int $0x80
  ret

What I wanted to write in equivalent in C is:

#include<stdio.h>
int main() {
  int arr[5];
  arr[0] = 5;
  arr[1] = 0;
  arr[2] = 1;
  arr[3] = 3;
  arr[4] = 4;
  int max = 0;
  for(int i = 0;i < 5;i++)
    if(max < arr[i])
      max = arr[i];
  printf("%d\n", max);
  return 0;
}

How can I implement a loop in GAS assembler? I am new to this and know very less about this. Please help.

JFMR
  • 23,265
  • 4
  • 52
  • 76
as2d3
  • 802
  • 2
  • 10
  • 27
  • 1
    A conditional jump is sorta common. Note that ECX is often used as a loop index, and has some extra instructions to support that. – Martin James Aug 24 '17 at 07:19
  • @MartinJames But how do I access the elements in the array inside the loop? – as2d3 Aug 24 '17 at 07:21
  • 1
    One way: use EBX as an offset. You are trying to write assembler without knowing the architecture and instruction set:( – Martin James Aug 24 '17 at 07:23
  • ..and especially addressing modes. – Martin James Aug 24 '17 at 07:24
  • @MartinJames Yes, I am a beginner in this. I assigned the values using -12(%ebp), --8(%ebp), etc. How do I access them in the loop? – as2d3 Aug 24 '17 at 07:25
  • @AbhishekAgrawal The memory operand `-20(%ebp,%eax,4)` refers to `arr[i]` as long as `i` is in `eax`. You can use it in moth instructions. – fuz Aug 24 '17 at 07:35
  • 1
    `subl -1, %eax` will subtract -1 from `eax`, which means `eax = eax - (-1)` which equals `eax = eax + 1` ... I have strong suspicion that's not what you wanted? Even worse, IIRC in AT&T syntax the "`-1`" is referring to memory content at address `-1`, so it will crash on illegal access. For constant you should use the `$` ahead of it. (I love AT&T syntax so much, that I can't even tell you, to remain polite) Probably wanted `subl $1, %eax` or `addl $-1, %eax`? If you want count-down from 5 to 0, you don't need `cmp $0, %eax`, the last subtraction by `sub/add/dec` will set zero flag: `jnz loop` – Ped7g Aug 24 '17 at 08:41
  • @Ped7g Thanks for your really important input. I have updated my code but I am having a segmentation fault at line ```movl $5, -20(%ebp)```. Can you help? – as2d3 Aug 24 '17 at 08:48
  • My new code is here : http://collabedit.com/yc4x8 – as2d3 Aug 24 '17 at 08:52
  • 1
    @Ped7g the horrible AT&T syntax is the main reason I only gave hints:) – Martin James Aug 24 '17 at 10:41

0 Answers0