scc

suckless C compiler
git clone git://git.suckless.org/scc
Log | Files | Refs | README | LICENSE

commit cf4d2d36e7ee668f37adf72cfc628882a0630a26
parent fd29c83f7281632dba2c210f488e8ccec173e604
Author: Roberto E. Vargas Caballero <k0ga@shike2.com>
Date:   Mon, 27 Feb 2017 08:37:16 +0100

[libc] Avoid overflow on INT_MIN in atoi()

The range for signed values in two complement is asimetric,
having one more number in the negative range than in the positive.
For this reason if the number is computed in positive INT_MIN
will overflow, because -INT_MIN overflows and --INT_MIN != INT_MIN.

Diffstat:
libc/src/atoi.c | 7++++---
1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/libc/src/atoi.c b/libc/src/atoi.c @@ -6,20 +6,21 @@ int atoi(const char *s) { - int n, sign = 1; + int n, sign = -1; while(isspace(*s)) ++s; switch(*s) { case '-': - sign = -1; + sign = 1; case '+': ++s; } + /* Compute n as a negative number to avoid overflow on INT_MIN */ for (n = 0; isdigit(*s); ++s) - n = 10 * n + (*s - '0'); + n = 10*n - (*s - '0'); return sign * n; }