Skip to content

Commit

Permalink
Avoid integer overflow
Browse files Browse the repository at this point in the history
val = -val will cause overflow when val = LLONG_MIN, and the result is
undefined. So the compiler could assume val != LLONG_MIN, and val will
always be positive after this:

if (val < 0) {
	val = -val;
}

So the later check if (n < 0) is ignored.

gcc -O2 uses this assumption, while gcc -O1 or clang doesn't.

Special case LLONG_MIN to avoid this overflow.
  • Loading branch information
zsx committed Aug 22, 2014
1 parent 492e558 commit 41bd1c6
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/core/f-math.c
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,14 @@
return 1;
}

#define MIN_I64_STR "-9223372036854775808"
if (val == MIN_I64) {
len = strlen(MIN_I64_STR);
if (maxl < len + 1) return 0;
COPY_MEM(buf, MIN_I64_STR, len + 1);
return len;
}

if (val < 0) {
val = -val;
*buf++ = '-';
Expand Down

0 comments on commit 41bd1c6

Please sign in to comment.