Unexpected ouput when trying to find minimum value in an array using x86 assembly

I'm a beginner following a book (Programming from the ground up) and this is my first assembly program:

.section .data

data_items: .long 3, 67, 34, 222, 45, 75, 54, 34, 44, 33, 22, 11, 66, 0

.section .text

.globl _start

_start:
    movl $0, %edi
    movl data_items(,%edi,4), %eax
    movl %eax, %ebx

start_loop:
    cmpl $0, %eax
    je loop_exit
    incl %edi
    movl data_items(,%edi,4), %eax
    cmpl %ebx, %eax
    jge start_loop
    movl %eax, %ebx
    jmp start_loop

loop_exit:
    movl $1, %eax
    int $0x80

%edi is used the keep track of the current index, %eax of the current value and %ebx of the current highest value.

This program originally found the highest value by jumping back if %eax was less than %ebx (meaning it didn't have to store the new value as the current highest) and I just changed it to jge instead of jle so it would only store %eax in %ebx if it encountered a smaller value.

My issue is that my program returns 0 instead of 3, which I expect would be the correct output. Shouldn't it exit when it encounters 0 because it checks if %eax is 0 at the start of every start_loop iteration and if so, jumps to loop_exit?

So in short: why is the output of this program 0 instead of 3?

edit: by output I mean the return code of %ebx when I call echo $?

Upvotes: 3

Views: 63

Answers (1)

Sep Roland
Sep Roland

Reputation: 39205

Shouldn't it exit when it encounters 0 because it checks if %eax is 0 at the start of every start_loop iteration

So you want to treat 0 as your list terminating value. This requires you to check for it as soon as you read each value. Your code has 2 instances of such a read and so requires 2 checks for the terminating value:

    ...
    movl data_items(,%edi,4), %eax
    movl %eax, %ebx
    cmpl $0, %eax
    je   loop_exit     ;List is empty, only terminator present
start_loop:
    incl %edi
    movl data_items(,%edi,4), %eax
    cmpl $0, %eax
    je loop_exit       ;End of list reached
    ...

Upvotes: 3

Related Questions