From 1dedd0ebca5fc19c7f08d244ed72a1abc57699ae Mon Sep 17 00:00:00 2001 From: Jan Nieuwenhuizen Date: Sun, 20 May 2018 08:33:06 +0200 Subject: [PATCH] mescc: Fix itoa. * lib/libc.c (itoa): Use function-static buffer. Increase to 12 to handle INT_MIN. (itoab): Likewise. --- lib/libc.c | 46 +++++++++++++++++++--------------------- scaffold/tests/52-itoa.c | 13 ++++++++---- 2 files changed, 31 insertions(+), 28 deletions(-) diff --git a/lib/libc.c b/lib/libc.c index 1427ba2d..40be8a44 100644 --- a/lib/libc.c +++ b/lib/libc.c @@ -91,28 +91,26 @@ atoi (char const *s) return abtoi (&p, 0); } -char itoa_buf[10]; - char const* itoa (int x) { - //static char itoa_buf[10]; - //char *p = buf+9; - char *p = itoa_buf; - p += 9; + static char itoa_buf[12]; + char *p = itoa_buf + 11; *p-- = 0; - //int sign = x < 0; // FIXME int sign = 0; - if (x < 0) sign = 1; - if (sign) - x = -x; + unsigned u = x; + if (x < 0) + { + sign = 1; + u = -x; + } do { - *p-- = '0' + (x % 10); - x = x / 10; - } while (x); + *p-- = '0' + (u % 10); + u = u / 10; + } while (u); if (sign && *(p + 1) != '0') *p-- = '-'; @@ -123,24 +121,24 @@ itoa (int x) char const* itoab (int x, int base) { - //static char itoa_buf[10]; - //char *p = buf+9; - char *p = itoa_buf; - p += 9; + static char itoa_buf[12]; + char *p = itoa_buf + 11; *p-- = 0; - //int sign = x < 0; // FIXME int sign = 0; - if (x < 0) sign = 1; - if (sign) - x = -x; + unsigned u = x; + if (x < 0) + { + sign = 1; + u = -x; + } do { - int i = x % base; + int i = u % base; *p-- = i > 9 ? 'a' + i - 10 : '0' + i; - x = x / base; - } while (x); + x = u / base; + } while (u); if (sign && *(p + 1) != '0') *p-- = '-'; diff --git a/scaffold/tests/52-itoa.c b/scaffold/tests/52-itoa.c index 634b2ab1..e2630038 100644 --- a/scaffold/tests/52-itoa.c +++ b/scaffold/tests/52-itoa.c @@ -30,16 +30,21 @@ test () puts ("\n"); puts ("t: itoa (33) == \"33\"\n"); - if (strcmp (itoa (33), "33")) return 1; + if (strcmp (itoa (33), "33")) + return 1; puts ("strcmp (itoa (-1), \"-1\")\n"); - if (strcmp (itoa (-1), "-1")) return 1; + puts (itoa (-1)); + if (strcmp (itoa (-1), "-1")) + return 2; puts ("strcmp (itoa (0), \"0\")\n"); - if (strcmp (itoa (0), "0")) return 1; + if (strcmp (itoa (0), "0")) + return 3; puts ("strcmp (itoa (1), \"1\")\n"); - if (strcmp (itoa (1), "1")) return 1; + if (strcmp (itoa (1), "1")) + return 4; return 0; }