My goal is to load values in a 5×5 matrix and compare each value and print out the largest number.
After running a debugger I get :
0x080480bb <+0>: mov esi,DWORD PTR [eax+edi*1]
0x080480be <+3>: jmp 0x804809d <loop>
segment .data
matrix db 1,62,3,44,35, \
61,52,43,45,55, \
17,23,37,74,65, \
13,12,93,94,95, \
31,21,13,14,25
segment .bss
holder resb 4
counter resb 4
segment .text
global _start
_start:
mov eax, matrix
call big
big:
mov esi, holder
mov edi, counter
mov edi, 0
jmp switch
loop:
inc edi
cmp esi, [eax + edi]
jg switch
cmp edi, 25
jle loop
mov eax, [esi]
sub eax, '0'
mov eax, 4
mov ebx, 1
mov ecx, esi
mov edx, 4
int 0x80
switch:
mov esi, [eax + edi]
jmp loop
exit:
mov eax, 1
xor ebx, ebx
int 0x80
I can see some problems in your code. Here’s the first one:
At this point, you’ve checked the whole matrix and want to write down the largest value found, which is already in esi, so you don’t have to dereference to get it. Also, you should be adding ‘0’ for numbers between 0 and 9, so the conversion is also wrong. And, one final thing, after converting you’re overwriting the value in eax, which is therefore lost.
The real segmentation fault, howewer, happens here,
Right after you write the result. The problem is that ecx should contain a pointer to the zero terminated string to write. Instead of that, you put in it the number you want to write, which is undefined behavior (it means everything might happen). Now, eax holds write’s return value, so my guess is that an error occurred and eax now contains -1, resulting in a seg. fault.
One simple work-around for that is adding a jmp exit after you write the value.
And, last but not least, (and as @user786653 said), “not handling your byte-sized data properly”. What does that mean? Basically, your matrix is an array of bytes, but every time you read from memory you pick up 4 bytes at time. The simplest solution is to declare your matrix as a double words array (dd or dword in place of db) and multiply by 4 the offset (example: mov eax, [ebx + ecx * 4]).
C’mon, don’t worry! Assembly is a difficult beast to play with 😉
EDIT:
The part which finds the greatest number is correct. You just have to fix the “output” part and the addressing stuff I said before. In my opinion, if you use the hex base for your numbers converting it to a printable string will be much easier (you can multiply by 2^n by shifting left by n places -> shl eax, 5 = eax *= 32)