checking for overflow

A

Arin Chaudhuri

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
 
A

Arin Chaudhuri

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
 
A

Arin Chaudhuri

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
 
E

Eric Sosman

Arin said:
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;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top