Divide by 0 exception when dividing 4 by 2 ?

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
Ankeraout
Member
Member
Posts: 25
Joined: Tue Feb 28, 2017 10:22 am

Divide by 0 exception when dividing 4 by 2 ?

Post by Ankeraout »

Hello,

I am currently running my 32-bit protected mode code in Bochs.
I have loaded GDT, IDT and PIC, and interrupts are enabled.

To write my itoa implementation, I have to use the DIV instruction, which calls int 0 everytime.

Here is my test code :

Code: Select all

mov eax, 4
mov ecx, 2
div ecx ;will call int0
This code calls my divide by 0 exception handler, and I don't know why.

Thanks by advance,
Ankeraout.
User avatar
Brendan
Member
Member
Posts: 8561
Joined: Sat Jan 15, 2005 12:00 am
Location: At his keyboard!
Contact:

Re: Divide by 0 exception when dividing 4 by 2 ?

Post by Brendan »

Hi,
Ankeraout wrote:Here is my test code :

Code: Select all

mov eax, 4
mov ecx, 2
div ecx ;will call int0
This code calls my divide by 0 exception handler, and I don't know why.
It's because the DIV instruction divides a 64-bit unsigned integer (in EDX:EAX) by a 32-bit divisor (in ECX in your case). You don't set EDX to zero, so you could be dividing a huge number (e.g. 0xFFFFFFFF00000004) by 2.

Also note that you get a "divide error" exception when the result doesn't fit in 32-bits (which includes "infinity"). If EDX was 2 or larger the result won't fit in 32-bits and...


Cheers,

Brendan
For all things; perfection is, and will always remain, impossible to achieve in practice. However; by striving for perfection we create things that are as perfect as practically possible. Let the pursuit of perfection be our guide.
Ankeraout
Member
Member
Posts: 25
Joined: Tue Feb 28, 2017 10:22 am

Re: Divide by 0 exception when dividing 4 by 2 ?

Post by Ankeraout »

Oh okay, I will test clearing EDX :D
Thank you !

EDIT : It works. Thanks !
Post Reply