[PATCH 3/3] tools/nolibc: make atoi() and atol() skip whitespace and accept '+'
From: Arav Verma
Date: Wed Nov 25 2026 - 13:15:06 EST
The C standard defines atoi() and atol() as strtol() with a fixed base
of 10, which skips leading whitespace and accepts an optional '+' or
'-' sign. nolibc only handles '-', so atoi(" 12") and atoi("+5") both
return 0.
Skip leading whitespace, accept '+' and add test cases.
Signed-off-by: Arav Verma <svav2021@xxxxxxxxx>
---
tools/include/nolibc/stdlib.h | 5 +++++
tools/testing/selftests/nolibc/nolibc-test.c | 6 ++++++
2 files changed, 11 insertions(+)
diff --git a/tools/include/nolibc/stdlib.h b/tools/include/nolibc/stdlib.h
index 1c5a914c0f231..cccb8922bde7c 100644
--- a/tools/include/nolibc/stdlib.h
+++ b/tools/include/nolibc/stdlib.h
@@ -66,9 +66,14 @@ long atol(const char *s)
unsigned long d;
int neg = 0;
+ while (isspace(*s))
+ s++;
+
if (*s == '-') {
neg = 1;
s++;
+ } else if (*s == '+') {
+ s++;
}
while (1) {
diff --git a/tools/testing/selftests/nolibc/nolibc-test.c b/tools/testing/selftests/nolibc/nolibc-test.c
index 971a7f48e016d..3062af07304a6 100644
--- a/tools/testing/selftests/nolibc/nolibc-test.c
+++ b/tools/testing/selftests/nolibc/nolibc-test.c
@@ -2097,6 +2097,12 @@ int run_stdlib(int min, int max)
CASE_TEST(limit_ptrdiff_min); EXPECT_EQ(1, PTRDIFF_MIN, sizeof(long) == 8 ? (ptrdiff_t) 0x8000000000000000LL : (ptrdiff_t) 0x80000000); break;
CASE_TEST(limit_ptrdiff_max); EXPECT_EQ(1, PTRDIFF_MAX, sizeof(long) == 8 ? (ptrdiff_t) 0x7fffffffffffffffLL : (ptrdiff_t) 0x7fffffff); break;
CASE_TEST(limit_size_max); EXPECT_EQ(1, SIZE_MAX, sizeof(long) == 8 ? (size_t) 0xffffffffffffffffULL : (size_t) 0xffffffffU); break;
+ CASE_TEST(atoi_simple); EXPECT_EQ(1, atoi("35"), 35); break;
+ CASE_TEST(atoi_negative); EXPECT_EQ(1, atoi("-35"), -35); break;
+ CASE_TEST(atoi_positive); EXPECT_EQ(1, atoi("+35"), 35); break;
+ CASE_TEST(atoi_space); EXPECT_EQ(1, atoi(" \t\n35"), 35); break;
+ CASE_TEST(atoi_space_negative); EXPECT_EQ(1, atoi(" -35"), -35); break;
+ CASE_TEST(atol_space_positive); EXPECT_EQ(1, atol(" +35"), 35L); break;
CASE_TEST(strtol_simple); EXPECT_STRTOX(1, strtol, "35", 10, 35, -1, 0); break;
CASE_TEST(strtol_positive); EXPECT_STRTOX(1, strtol, "+35", 10, 35, -1, 0); break;
CASE_TEST(strtol_negative); EXPECT_STRTOX(1, strtol, "-35", 10, -35, -1, 0); break;
--
2.47.3