I wrote this basic linux x86 assembly app. I expect it to return 3 when I do echo $? however the status is always 0. What am I doing wrong?
.section .data
data_items:
.long 3,67,34,222,45,2,54,34,44,33,22,11,66,0
.section .text
.global _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
Note: %ebx always contains the status code, and it should contain the min value by exit time.
Fixed:
_start:
movl $0, %edi
movl data_items(,%edi,4), %ebx
start_loop:
incl %edi
movl data_items(, %edi, 4), %eax
cmpl $0, %eax
je loop_exit
cmpl %ebx, %eax
jge start_loop
movl %eax, %ebx
Advertisement
Answer
The issue is that the terminating zero also participates in the minimum calculation. You check for that zero only after you have already done the check for the minimum. Learn to use a debugger to step through your code.
Consider what happens when you arrive at the last item, the 66. Follow the code from the start_loop. Obviously 66 is not 0 so it continues, increments the index and fetches the next number which is the zero. This is of course less than the minimum so far, thus it’s stored into ebx and we end up at start_loop again, which correctly detects the terminating condition. However ebx is already zeroed.