Integer Overflow klocwork analysis - java

I have the following lines of code and when I run klocwork analysis on my project I get the following error
SV.INT_OVF: Tainted data 'Long.parseLong(...)' that comes from 'br.readLine()' is used in an arithmetic operation and can cause an integer overflow or unexpected result
My code
while (line = br.readLine() != null) {
long timestamp = timescale * Long.parseLong(line.substring(1, line.length()));
}
How can I refactor this code to avoid possible overflow
Thanks

You can use BigInteger to avoid an overflow.
Whether you should is another question.
I would look at what is a sane range for these values and validate your inputs first. Most likely the widest range of sane values won't produce an overflow (or if it does, you have to use BigInteger)

Related

Why does a compilation error occur when declaring a stack containing a Long object in Java, popping a number, and then casting it to long? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
There is a stack containing a long-sized range, and you want to multiply two values ​​by popping them from the stack.
Stack<Long> s = new Stack<>();
s.push(1000000000);
s.push(1000000000);
long result = (long) s.pop() * (long) s.pop();
However, doing such an operation gives an error.
Exception in thread "main" java.lang.ClassCastException:
java.lang.Integer cannot be cast to java.lang.Long
what's wrong with this code
There are a few issues here:
Stack<Long> s = new Stack();
This is actually a partially-raw type. You need to add <> on the right-hand side:
Stack<Long> s = new Stack<>();
(NB: I can remember at some point in the past encountering this as behaving like a raw type. I tried it on ideone just now, and it behaves like a non-raw type. I forget the exact situation in which it works like I describe - perhaps it was on Eclipse's compiler...? Anyway, the point is: use the diamond, and it's correct).
Because that's raw, it leads on to the next point:
s.push(1000000000);
1000000000 is an int literal. You shouldn't actually be able to add this to a Stack<Long>; you only can because of the partial rawness. int cannot be autoboxed to Long: you have to explicitly box it, or at least cast to long.
Stack stores objects; int 1000000000 gets boxed to Integer 1000000000, and put into the stack.
You need to push long literals (or Longs) instead:
s.push(1000000000L); // Note the L suffix
(long) s.pop()
Actually, this could almost work, if you'd written it like this:
s.pop().longValue()
But you're still getting Integers out of it as it stands.
Note that if you'd added the values correctly, you wouldn't need to put the (long) casts: Java would automatically unbox the values:
long result = s.pop() * s.pop();

calculate factorial recursive in functional style Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I try to calculate factorial in a functional style.
I did this:
private static Function<BigInteger, BigInteger> factorial = x -> BigInteger.ONE.equals(x)
? BigInteger.ONE
: x.multiply(Main.factorial.apply(x.subtract(BigInteger.ONE)));
And I have got StackOverflowError when trying to get 11111!
BUT when I calculate factorial using this method:
private static BigInteger factorial(BigInteger request) {
if (BigInteger.ONE.equals(request)) return BigInteger.ONE;
else return request.multiply(factorial(request.subtract(BigInteger.ONE)));
}
I can get the result without StackOverflowError.
Is functional style less effective? Why?
There are twice as many calls in the functional style as compared to function calls. see image.
So while the stack size increases to 11,111 calls in latter, it increases by over 22,222 calls in functional style. I believe stack limit in your environment should be between 11111 and 22222 so that explains why it breaks. So in this sense Functional style seems inefficient.
You can increase the stack size using -Xss described in the below link.
Or, better to use tail recursion which looks something like this:
private static BiFunction<BigInteger, BigInteger, BigInteger> factorialTR = (n, acc) -> BigInteger.ONE.equals(x)
? BigInteger.ONE
: Main.factorialTR.apply(x.subtract(BigInteger.ONE), acc * n));
This will still cause StackoverflowError in Java as it does not support tail call optimization. But Scala, lisp do, there you wont get one.
Refs
Tail-recursive factorial
Leetcode explanation(requires login)
max stack depth
Your terminology is somewhat confusing. Both of the examples you showed are written in a functional style: there are no side-effects, no mutable state, no loops. Both examples are referentially transparent.
Also, you seem to be under the impression that only one of those examples will throw a StackOverflowError. That is not the case. Both of those will eventually blow the stack.
In fact, in my testing, both of those blew the stack pretty much at the same value.
For the lambda version, I ran multiple tests, and the stack overflow happened at slightly different values each time, the smallest and biggest ones were around 11000 and around 15300.
For the method version, the stack overflow happened pretty consistently between 13901 and 13907.
Initially, I thought that the lambda version would consistently overflow earlier than the method version, because it uses much more complex runtime machinery (LambdaMetaFactory, method handles, call sites, invokedynamic) which increases the stack size. But, it looks like more than increase the stack size, it increases the variance due to its bigger reliance on runtime optimizations and heuristics.
By the way, your code (both versions) has the same two bugs (which are actually the same bug): it doesn't handle factorial of zero (which is one) and it runs into an infinite recursion for negative numbers. A more correct version would be something like:
private static Function<BigInteger, BigInteger> factorial =
x ->
x.compareTo(BigInteger.ZERO) < 0
? throw new ArgumentError()
: BigInteger.ZERO.equals(x)
? BigInteger.ONE
: x.multiply(App.factorial.apply(x.subtract(BigInteger.ONE)));
private static BigInteger factorial(BigInteger request) {
if (request.compareTo(BigInteger.ZERO) < 0) throw new ArgumentError;
if (BigInteger.ZERO.equals(request)) return BigInteger.ONE;
else return request.multiply(factorial(request.subtract(BigInteger.ONE)));
}

Factorial for big number in java [duplicate]

This question already has answers here:
StackOverflowError computing factorial of a BigInteger?
(5 answers)
Closed 6 years ago.
I've been working around with this recursive function but couldn't find myself which led me to overflow error and it keeps coming around. I've already tried casting to BigInteger also but nothing special is coming. I don't see any warning or syntax error in my Eclipse IDE. I had to submit an efficient algorithm for big numbers. thanks in advance. :-)
public static BigInteger factorial(int n)
{
return n > 2 ? new BigInteger(n+"").multiply(factorial(n-1)) : new BigInteger(n+"");
}
The problem
You're getting the error because the computer has to remember every method call you make (and other information) until that method call is finished, and there's only so much space on the "stack" set aside to remember all that.
You recurse so many times that you overflow the stack space set up to remember method calls that are in progress. That's called a stack overflow.
A possible solution
A reasonably-efficient algorithm is to use a simple loop. This has the side benefit of not causing stack overflows, since you don't create more method calls over and over again, you just do stuff inside the first method call.
You should also use BigInteger.valueOf(n) instead of new BigInteger(n+""):
public static BigInteger factorial(int n) {
BigInteger result = BigInteger.ONE;
for (; n > 1; n--) {
result = result.multiply(BigInteger.valueOf(n));
}
return result;
}
This takes my computer about 6 seconds to compute 100,000!
More efficient solutions
There are faster algorithms than this. See another question and its links for more details.

Parsing of math expression gives wrong tree

So the code is rather complicated so ill try to do some neat pseudo code that covers the most important issues. I'm trying to parse a math expression. For example: 1-5*(-2)+3 = 14
The syntax that im using is:
expression = term OR term+expression OR term-expression
term = factor OR factor*term OR factor/term
factor = number OR -factor OR (expression)
I have written a piece of code which checks if an expression follows this syntax and it works well for checking the expressions but not for calculating it.
The pseudo code goes something like:
double readExpression()
number = readTerm()
if token == +
number2 = readExpression()
return number + number2
else if token == -
number2 = readExpression()
return number - number2
else
return number
...
(The code for readTerm() is identical to readExpression() in structure)
...
double readFactor()
if token == number
return number
else if token == -
number = readFactor()
return (-1)*number
else if token == (
number = readExpression()
return number
else raise exception
If I do the above calculation with this code it will give me a tree that looks like this:
So anyway, as you matematicians have figured out byt now, the expression should give 14 and not 8 as the tree suggests. I have noticed the that the problem arises when there are minus-signs in front of expressions since affect the whole right term i this problem whilst they should only affect the middle-term.
Ive been thinking like crazy for weeks and thought about solutions for this and looked at other codes and so on. Please dont toss a bunch of links on me if they are not really really simple and good since ive been browsing alot myself on tree traversals and other relevant topics.
What could i do at this stage? As I said, my program can tell if its right or wrong. So now I only need to parse a correct expression. Should I write another class for the parsing of the correct expression? Is it easier? Anyway I dont see how that code would look different than this.
Yes I would parse the equation, it just looks like you miss a key part of the order of operations/parsing. You need to include an additional check for double negatives.
The key factor here is that: In a situation with two identical operators then the left most operation is always carried out first.
First lets narrow down the issue.
This 1-5*(-2)+3 is equal to 1--10+3.
Now for our purposes lets assign a positive to the first operator because it helps illustrate a point:
1--10+3 is the same as +1--10+3
Now if we where to run +1--10+3 through a correct parser we would know that this -- is equal to + but only when used in the following situation:
+X--Y = X+Y
So now our parser has turned the original expression of 1--10+3 into 1+10+3 and we know that is equal to 14.
So all up: Yes you need a parser, but pay special attention to how +X--Y and X+Y work.
Also take a look at this answer: https://stackoverflow.com/a/26227947/1270000

How to find and handle binary/numerical overflow in J2ME

I am building a unit convertor program that uses the MathFP library.
Typically unit conversion occurs in the formula of:
U1 (unit1) * K (constant) = U2 (unit2)
I want to be able to detect when the an int has over/underflowed?
How can I detect when this has occured and gracefully handle the problem. Ideally I would be looking for a generic solution, as I would want to handle overflow with primitives of type long:
The only idea I have is:
int largeOne = bigNum;
int largeTwo = anotherbigNum;
//complete math operation
long l = largeOne * largeTwo;
if(l > Integer.MAX_SIZE){
System.out.println("Overflow");
//handle error
}
Should I be using a different primitive data type for these conversions, such as double?
Thanks in advance for your help
You could check if the result is negative, or positive (depending on largeOne and largeTwo signs) but it would be a guess work.
I found another way, you could manually multiply your two numbers with an algorithm.
Resources :
Wikipedia - Multiplication algorithm
On the same topic :
how to write own multiplication of big numbers ?
You could switch to using the BigDecimal class which has much better handling for overflow/underflow than the int/long primitives in Java. The int/long values are a special case that are not classes and as a result miss out on advantages of OOP.

Categories

Resources