From 2a5f48c3fda7b54e8595d26901a2f2852fcfbbb3 Mon Sep 17 00:00:00 2001 From: Sunny Date: Mon, 10 Jul 2023 12:56:16 +0000 Subject: [PATCH] libs/libc/stdlib: fix strtoul,strtoull bugs when value outside range Prototype: unsigned long strtoul(FAR const char *nptr, FAR char **endptr, int base); unsigned long long strtoull(FAR const char *nptr, FAR char **endptr, int base); If endptr is not NULL, strtoul()/strtoull() should store the address of the first invalid character in *endptr. And if the correct value is outside the range of representable values, {ULONG_MAX} or {ULLONG_MAX} shall be returned and errno set to [ERANGE]. With such code: strtoul("34592348345343453453455645765736575865767", &endptr, 10); It indeed returns ULONG_MAX and sets errno to ERANGE. But after strtoul return, endptr points to "3455645765736575865767", not NULL. Signed-off-by: Sunny --- libs/libc/stdlib/lib_strtoul.c | 5 +++++ libs/libc/stdlib/lib_strtoull.c | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/libs/libc/stdlib/lib_strtoul.c b/libs/libc/stdlib/lib_strtoul.c index 92f6bcc08c7..3f4959aab79 100644 --- a/libs/libc/stdlib/lib_strtoul.c +++ b/libs/libc/stdlib/lib_strtoul.c @@ -103,6 +103,11 @@ unsigned long strtoul(FAR const char *nptr, FAR char **endptr, int base) nptr++; } + while (lib_isbasedigit(*nptr, base, &value)) + { + nptr++; + } + if (sign == '-') { accum = (~accum) + 1; diff --git a/libs/libc/stdlib/lib_strtoull.c b/libs/libc/stdlib/lib_strtoull.c index 156e557d762..b3b68045163 100644 --- a/libs/libc/stdlib/lib_strtoull.c +++ b/libs/libc/stdlib/lib_strtoull.c @@ -107,6 +107,11 @@ unsigned long long strtoull(FAR const char *nptr, nptr++; } + while (lib_isbasedigit(*nptr, base, &value)) + { + nptr++; + } + if (sign == '-') { accum = (~accum) + 1;