Jump to content


Check out our Community Blogs





- - - - -

DIV 0 is Not the Only Way to Fail (Apparently)

Posted by RhetoricalRuvim, 25 March 2013 · 2081 views

assembly language div idiv divide by 0 divide by 1 fail exception
Hello everyone.

I just discovered something while trying to debug one of my assembly language programs. This is probably not new information for some people, but perhaps someone might find this useful to know.

The thing is: dividing by 0 is not the only way to raise an exception while executing the DIV instruction; dividing by 1 is just about as bad.

Take, for instance, the following code:
#include <stdio.h> 

int main (){ 
	long a; 
	asm { 
		mov ax, 256 
		mov cl, 1 
		div cl 
		mov dword ptr [a], eax 
	} 
	printf ("%d", a); 
}
; at least on my computer, that code fails.

However, here's code that works:
#include <stdio.h> 

int main (){ 
	long a; 
	asm { 
		mov ax, 256 
		mov cl, 2 
		div cl 
		mov dword ptr [a], eax 
	} 
	printf ("%d", a); 
}
The major drawback to assembly language is that you oftentimes never know what is wrong. It could be a bad pointer, or perhaps it's a stack imbalance. Or maybe it's something similar to what happened today.

Whatever the case, the lesson for me (or anyone who finds this useful) would be: when dividing using the DIV or IDIV instructions, don't just check for 0 in the divisor - check for 1 as well.

  • 1



The reason your code fails is due to this line:

mov dword ptr [a], eax 

When CPU executes div cl it divides AX by CL and place result in AL; the remainder is stored in AH. Besides you have not cleared hiword of EAX so it probably contains garbage.

 

My suggestion is: read more asm documentation, because if you use instructions and you don't know what do they do, you will never know what is wrong.

You can find a short introduction here:

http://en.wikibooks....mbly/Arithmetic

    • 0
You think so?

Okay, let's try taking that line out:
#include <stdio.h> 

int main (){ 
	long a; 
	asm { 
		mov ax, 256 
		mov cl, 1 
		div cl 
		// mov dword ptr [a], eax 
	} 
	printf ("%d", a); 
}
The new code fails also.

And because of the fact that 'div cl' only uses 'al' and 'ah' , the top half of EAX doesn't even matter.
    • 0

I guess I have missunderstood what you mean by 'fail'. I was writing why your code return invalid value, but the next thing is div causes divide error, as result doesn't fit in AL. This has nothing to do with divide by 1. The same error may be raised by

mov ax, 600
mov cl, 2
div cl 
    • 1

My Picture

0 user(s) viewing

0 members, 0 guests, 0 anonymous users

Categories