Simple assembly algorithm to find the largest number - Why is it returning the wrong number?
I am working on a simple routine that will loop through a list of numbers and return the max. It is always returning 11 and I cannot see what's wrong with my logic. To test the routine I have a list of numbers (data_items) that I am looping through. What am I doing wrong here?
.section .data
data_items: #these are the data items
.long 3,67,34,222,45,75,857,858,983,11,55,43,23,123,785,4356,0
.section .text
.globl _start
_start:
movl $0, %edi #move 0 into the index register
movl data_items(,%edi,4), %eax #load the first byte of data
movl %eax, %ebx #since this is the first item, %eax is the biggest
start_loop:
cmpl $0, %eax #check to see if we've hit the end
je loop_exit
incl %edi #load the next value
movl data_items(,%edi,4), %eax
cmpl %ebx, %eax #compare values
jle start_loop #jump to the start of the loop if the value is not larger
movl %eax, %ebx #move 开发者_如何学JAVAthe value as the largest
jmp start_loop #jump to the loop beginning
loop_exit:
movl $1, %eax #1 is the exit() syscall
int $0x80
Unix based operating systems only support 8-bit return value (so 0-255).
So your program does find the maximum value, and store it in %ebx
, but you cannot return it as the program's exit code. I ran your program without the numbers that are bigger than 255 and it worked correctly.
There's nothing wrong with your logic at all. When I enter that code into qq.s
and execute the following:
pax$ as -o qq.o qq.s
pax$ ld -o qq qq.o
pax$ gdb qq
GNU gdb (Ubuntu/Linaro 7.2-1ubuntu11) 7.2
Copyright (C) 2010 Free Software Foundation, Inc.
... blah blah blah ...
Reading symbols from /home/pax/qq...(no debugging symbols found)...done.
(gdb) break loop_exit
Breakpoint 1 at 0x8048097
(gdb) run
Starting program: /home/pax/qq
Breakpoint 1, 0x08048097 in loop_exit ()
(gdb) info reg ebx
ebx 0x1104 4356
(gdb) _
In other words, the correct value is being loaded into ebx
.
two points (1) when debugging and getting an unreasonable answer, remove that value from your test data, so in this case remove the 11 from your data and see what happens
(2) I just checked the value 4356(10) and displayed it in hex and got 1104(16), so I am thinking your return code is only getting the left byte of a 16 bit value (4356).
精彩评论