shithub: scc

Download patch

ref: 022532e3e74a94ff9a194378c5a9f7a4904d82d3
parent: 849b7a5e8aa295683e330c547b116e4a56c87db5
author: Roberto E. Vargas Caballero <k0ga@shike2.com>
date: Mon Feb 27 03:37:16 EST 2017

[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.

--- a/libc/src/atoi.c
+++ b/libc/src/atoi.c
@@ -6,7 +6,7 @@
 int
 atoi(const char *s)
 {
-	int n, sign = 1;
+	int n, sign = -1;
 
 	while(isspace(*s))
 		++s;
@@ -13,13 +13,14 @@
 
 	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;
 }