Starting to teach myself assembly (NASM) I wanted to know how to divide 2 numbers (For instance on Windows).
My code looks like this but it crashes.
global _main
extern _printf
section .text
_main:
mov eax, 250
mov ebx, 25
div ebx
push ebx
push message
call _printf
add esp , 8
ret
message db "Value is = %d", 10 , 0
I wonder what's really wrong? It doesn't even display the value after the division.
Your instruction div ebx
divides the register pair edx:eax
(which is an implicit operand for this instruction) by the provided source operand (i.e.: the divisor).
mov edx, 0
mov eax, 250
mov ecx, 25
div ecx
In the code above edx:eax
is the dividend and ecx
is the divisor.
After executing the div
instruction the register eax
contains the quotient and edx
contains the remainder.
I am using the register ecx
instead of ebx
for holding the divisor because, as stated in the comments, the register ebx
has to be preserved between calls. Otherwise it has to be properly saved before being modified and restored before returning from the corresponding subroutine.
As stated in one comment, if the quotient does not fit within the rage of the quotient register (eax
in this case), a divide by zero error does occur.
This may explain why your program is crashing: since the register edx
is not being set prior to executing the div
instruction, it might contain a value so large, that the resulting quotient doesn't fit in the eax
register.