Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Avoid Integer Overflow through Multiplication without Typecasting?

Please consider the following code:

unsigned int var1 = 4294967295;

unsigned int var2 = 1000000;

unsigned int var3;

var3 = some_expression - (var1*var2)/some_expression;

Bug:

In the expression for var3, the value:

(var1*var2) is being truncated to a 32-bit Integer (since it is obtained by multiplying 2 32-bit Integers).

Possible Fix:

var3 = some_expression - ((unsigned long int)var1*var2)/some_expression;

Problem:

Solaris does NOT accept this typecasting & throws the following error:

"conversion to non-scalar type requested"

Can I fix this issue without typecasting?

like image 830
Sandeep Singh Avatar asked Sep 13 '26 21:09

Sandeep Singh


1 Answers

Introduce an intermediate variable:

unsigned int var1 = 4294967295U;
unsigned int var2 = 1000000U;
unsigned int var3;

{
  unsigned long int vartmp = var1;
  vartmp *= var;

  var3 = some_expression - vartmp/some_expression;
}
like image 132
alk Avatar answered Sep 15 '26 10:09

alk