Bug? overflow check in Numbers.minus

12 views
Skip to first unread message

Achim Passen

unread,
Jan 8, 2009, 2:07:52 PM1/8/09
to clo...@googlegroups.com
Hi all!

I encountered some corner cases where overflow checking for "-"
doesn't work as I would expect:

user=> (- Integer/MAX_VALUE Integer/MIN_VALUE)
-1
user=> (- Long/MAX_VALUE Long/MIN_VALUE)
-1

The problem seems to be that negating MIN_VALUE yields MIN_VALUE
again, so it slips through the overflow check (see below).

Shall I add that to the issues list?

Kind regards,
achim

src/jvm/clojure/lang/Numbers.java
===================================================================
--- src/jvm/clojure/lang/Numbers.java (revision 1205)
+++ src/jvm/clojure/lang/Numbers.java (working copy)
@@ -1740,7 +1740,7 @@

static public int minus(int x, int y){
int ret = x - y;
- if ((ret ^ x) < 0 && (ret ^ -y) < 0)
+ if (((ret ^ x) < 0 && (ret ^ -y) < 0) || (y == Integer.MIN_VALUE))
return throwIntOverflow();
return ret;
}
@@ -1847,7 +1847,7 @@

static public long minus(long x, long y){
long ret = x - y;
- if ((ret ^ x) < 0 && (ret ^ -y) < 0)
+ if (((ret ^ x) < 0 && (ret ^ -y) < 0) || (y == Long.MIN_VALUE))
return throwIntOverflow();
return ret;
}

Chouser

unread,
Jan 9, 2009, 11:25:06 PM1/9/09
to clo...@googlegroups.com
On Thu, Jan 8, 2009 at 2:07 PM, Achim Passen <achim....@gmail.com> wrote:
>
> Hi all!
>
> I encountered some corner cases where overflow checking for "-"
> doesn't work as I would expect:
>
> user=> (- Integer/MAX_VALUE Integer/MIN_VALUE)
> -1
> user=> (- Long/MAX_VALUE Long/MIN_VALUE)
> -1
>
> The problem seems to be that negating MIN_VALUE yields MIN_VALUE
> again, so it slips through the overflow check (see below).
>
> Shall I add that to the issues list?

I think you should go ahead. I don't see how this could not be a bug.

--Chouser

Frantisek Sodomka

unread,
Jan 29, 2009, 10:32:12 AM1/29/09
to Clojure
user=> (- Integer/MAX_VALUE Integer/MIN_VALUE)
java.lang.ArithmeticException: integer overflow (NO_SOURCE_FILE:0)
user=> (- Long/MAX_VALUE Long/MIN_VALUE)
java.lang.ArithmeticException: integer overflow (NO_SOURCE_FILE:0)

Is this behavior correct?

Frantisek


On Jan 10, 5:25 am, Chouser <chou...@gmail.com> wrote:
Reply all
Reply to author
Forward
0 new messages