diff --git a/libs/libc/stdlib/lib_strtoul.c b/libs/libc/stdlib/lib_strtoul.c index 29ca5c4ece..1ee1de21e5 100644 --- a/libs/libc/stdlib/lib_strtoul.c +++ b/libs/libc/stdlib/lib_strtoul.c @@ -69,8 +69,9 @@ unsigned long strtoul(FAR const char *nptr, FAR char **endptr, int base) { unsigned long accum = 0; - unsigned long prev; + unsigned long limit; int value; + int last_digit; char sign = 0; if (nptr) @@ -98,22 +99,24 @@ unsigned long strtoul(FAR const char *nptr, FAR char **endptr, int base) } else { + limit = ULONG_MAX / base; + last_digit = ULONG_MAX % base; + /* Accumulate each "digit" */ while (lib_isbasedigit(*nptr, base, &value)) { - prev = accum; - accum = accum * base + value; - nptr++; - /* Check for overflow */ - if (accum < prev) + if (accum > limit || (accum == limit && value > last_digit)) { set_errno(ERANGE); accum = ULONG_MAX; break; } + + accum = accum * base + value; + nptr++; } if (sign == '-') diff --git a/libs/libc/stdlib/lib_strtoull.c b/libs/libc/stdlib/lib_strtoull.c index 4e27a1fab4..735e90c60d 100644 --- a/libs/libc/stdlib/lib_strtoull.c +++ b/libs/libc/stdlib/lib_strtoull.c @@ -68,11 +68,13 @@ * ****************************************************************************/ -unsigned long long strtoull(FAR const char *nptr, FAR char **endptr, int base) +unsigned long long strtoull(FAR const char *nptr, + FAR char **endptr, int base) { unsigned long long accum = 0; - unsigned long long prev; + unsigned long long limit; int value; + int last_digit; char sign = 0; if (nptr) @@ -100,22 +102,24 @@ unsigned long long strtoull(FAR const char *nptr, FAR char **endptr, int base) } else { + limit = ULLONG_MAX / base; + last_digit = ULLONG_MAX % base; + /* Accumulate each "digit" */ while (lib_isbasedigit(*nptr, base, &value)) { - prev = accum; - accum = accum * base + value; - nptr++; - /* Check for overflow */ - if (accum < prev) + if (accum > limit || (accum == limit && value > last_digit)) { set_errno(ERANGE); accum = ULLONG_MAX; break; } + + accum = accum * base + value; + nptr++; } if (sign == '-')