Page 1 of 1

Divide by 0 exception when dividing 4 by 2 ?

Posted: Thu Mar 30, 2017 2:52 am
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.

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

Posted: Thu Mar 30, 2017 2:58 am
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

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

Posted: Thu Mar 30, 2017 3:04 am
by Ankeraout
Oh okay, I will test clearing EDX :D
Thank you !

EDIT : It works. Thanks !