checking for overflow

  • Follow


Hi,
Is this code which checks if a and b when multiplied overflow correct?

/*begin code*/
#include <stdio.h>
#include <limits.h>

int check_overflow(unsigned long a,unsigned long b)
{
    unsigned long  t=ULONG_MAX/b;   
    unsigned long t1;
    t1=ULONG_MAX-t*b;
    if ( (a > t) || ((a == t) && (t1 > 0)) ) return 1;
    return 0;  
    /* return ( (a > t) || ((a == t) && (t1 > 0)) );*/
}
/*end code*/

thanks in advance,
Arin
0
Reply arin_chaudhuri_spam (10) 6/5/2004 10:31:56 AM

On Sat, 5 Jun 2004, Arin Chaudhuri wrote:

> Hi,
> Is this code which checks if a and b when multiplied overflow correct?
>
> /*begin code*/
> #include <stdio.h>
> #include <limits.h>
>
> int check_overflow(unsigned long a,unsigned long b)
> {
>     unsigned long  t=ULONG_MAX/b;
>     unsigned long t1;
>     t1=ULONG_MAX-t*b;
>     if ( (a > t) || ((a == t) && (t1 > 0)) ) return 1;
>     return 0;
>     /* return ( (a > t) || ((a == t) && (t1 > 0)) );*/
> }
> /*end code*/
>
> thanks in advance,
> Arin
>
My mistake.
Checking (a>t) should be sufficient.
Sorry.

#include <stdio.h>
#include <limits.h>

int check_overflow(unsigned long a,unsigned long b)
{
    unsigned long  t=ULONG_MAX/b;
    return (t>a);
}


Arin

0
Reply achaudh (2) 6/5/2004 11:29:16 AM


On Sat, 5 Jun 2004, Arin Chaudhuri wrote:
[snip]

I am having a bad day, I meant


 #include <stdio.h>
 #include <limits.h>

 int check_overflow(unsigned long a,unsigned long b)
 {
     unsigned long  t=ULONG_MAX/b;
     return (t<a);
 }


 Arin


0
Reply achaudh (2) 6/5/2004 11:31:24 AM

Arin Chaudhuri wrote:
> On Sat, 5 Jun 2004, Arin Chaudhuri wrote:
> [snip]
> 
> I am having a bad day, I meant
> 
> 
>  #include <stdio.h>
>  #include <limits.h>
> 
>  int check_overflow(unsigned long a,unsigned long b)
>  {
>      unsigned long  t=ULONG_MAX/b;
>      return (t<a);
>  }

     This looks almost right: It returns 1 if the product
of `a' and `b' would exceed `ULONG_MAX', or 0 if it would
not.  However, it will malfunction if `b' is zero.  A
possible fix:

	int check_overflow(unsigned long a, unsigned long b) {
	    return b > 0 && a > ULONG_MAX / b;
	}

-- 
Eric.Sosman@sun.com

0
Reply Eric.Sosman (4228) 6/7/2004 2:11:24 PM

3 Replies
42 Views

(page loaded in 0.3 seconds)


Reply: