[hackers] [scc] [libc] Avoid overflow on INT_MIN in atoi() || Roberto E. Vargas Caballero

From: <git_AT_suckless.org>
Date: Mon, 27 Feb 2017 08:39:56 +0100 (CET)

commit cf4d2d36e7ee668f37adf72cfc628882a0630a26
Author: Roberto E. Vargas Caballero <k0ga_AT_shike2.com>
AuthorDate: Mon Feb 27 08:37:16 2017 +0100
Commit: Roberto E. Vargas Caballero <k0ga_AT_shike2.com>
CommitDate: Mon Feb 27 08:37:16 2017 +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.

diff --git a/libc/src/atoi.c b/libc/src/atoi.c
index b484e1e..212b6fb 100644
--- a/libc/src/atoi.c
+++ b/libc/src/atoi.c
_AT_@ -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;
 }
Received on Mon Feb 27 2017 - 08:39:56 CET

This archive was generated by hypermail 2.3.0 : Mon Feb 27 2017 - 08:48:16 CET