Question:
good guys ,
I'm new to assembly, I'm having problems doing division. When I compile the program from the command line, I get this Floating point exception error.
.section .data
.global op1
.global op2
.global resultado
.section .text
.global Conta
Account:
prologue
pushl %ebp
movl %esp, %ebp
movl op1, %edx
movl op2, %eax
divl %edx, %eax
movl %eax, resultado
epilogue
movl %ebp, %esp
popl %ebp
ret
Answer:
The div
instruction, divides the value (unsigned integer) stored in the pair of registers edx:eax
(dividend – 64 bits) by the destination operator (can be a register or memory location – 32 bits), and stores the quotient in eax
and the rest in edx
.
Since you are storing the value of op1
in edx
, and dividing edx:eax
by edx
(which is part of the dividend), the result of the division is probably greater than 32 bits and this generates the Floating point exception error (or divide error , as per the Intel manual ).
A possible solution to the problem is to reset the edx
register and use a register other than edx
and eax
to store the divisor (if the division you are trying to do is 32 bits and not 64 bits).
Here is an example of your changed code, using the ebx
register to store the divider:
Conta:
push %ebp
movl %esp, %ebp
movl op2, %ebx # armazena o divisor em ebx
xorl %edx, %edx # zera edx (parte alta do dividendo)
movl op1, %eax # armazena o dividendo (parte baixa) em eax
divl %ebx, %eax # divide edx:eax por ebx
movl %eax, resultado
movl %ebp, %esp
pop %ebp
ret
Execution example: division 13 by 3:
Conta () at teste.a:30
30 movl op2, %ebx
(gdb)
31 xorl %edx, %edx
(gdb)
32 movl op1, %eax
(gdb)
33 divl %ebx, %eax
(gdb) info registers
eax 0xd 13 <----- parte "baixa" do dividendo
ecx 0x0 0
edx 0x0 0 <----- parte "alta" do dividendo
ebx 0x3 3 <----- divisor
...
(gdb) s
34 movl %eax, resultado
(gdb) info registers
eax 0x4 4 <----- quociente
ecx 0x0 0
edx 0x1 1 <----- resto
ebx 0x3 3
...