mescc: Fix itoa.

* lib/libc.c (itoa): Use function-static buffer.  Increase to 12 to
  handle INT_MIN.
  (itoab): Likewise.
This commit is contained in:
Jan Nieuwenhuizen 2018-05-20 08:33:06 +02:00
parent 03ba0e18df
commit 1dedd0ebca
No known key found for this signature in database
GPG key ID: F3C1A0D9C1D65273
2 changed files with 31 additions and 28 deletions

View file

@ -91,28 +91,26 @@ atoi (char const *s)
return abtoi (&p, 0); return abtoi (&p, 0);
} }
char itoa_buf[10];
char const* char const*
itoa (int x) itoa (int x)
{ {
//static char itoa_buf[10]; static char itoa_buf[12];
//char *p = buf+9; char *p = itoa_buf + 11;
char *p = itoa_buf;
p += 9;
*p-- = 0; *p-- = 0;
//int sign = x < 0; // FIXME
int sign = 0; int sign = 0;
if (x < 0) sign = 1; unsigned u = x;
if (sign) if (x < 0)
x = -x; {
sign = 1;
u = -x;
}
do do
{ {
*p-- = '0' + (x % 10); *p-- = '0' + (u % 10);
x = x / 10; u = u / 10;
} while (x); } while (u);
if (sign && *(p + 1) != '0') if (sign && *(p + 1) != '0')
*p-- = '-'; *p-- = '-';
@ -123,24 +121,24 @@ itoa (int x)
char const* char const*
itoab (int x, int base) itoab (int x, int base)
{ {
//static char itoa_buf[10]; static char itoa_buf[12];
//char *p = buf+9; char *p = itoa_buf + 11;
char *p = itoa_buf;
p += 9;
*p-- = 0; *p-- = 0;
//int sign = x < 0; // FIXME
int sign = 0; int sign = 0;
if (x < 0) sign = 1; unsigned u = x;
if (sign) if (x < 0)
x = -x; {
sign = 1;
u = -x;
}
do do
{ {
int i = x % base; int i = u % base;
*p-- = i > 9 ? 'a' + i - 10 : '0' + i; *p-- = i > 9 ? 'a' + i - 10 : '0' + i;
x = x / base; x = u / base;
} while (x); } while (u);
if (sign && *(p + 1) != '0') if (sign && *(p + 1) != '0')
*p-- = '-'; *p-- = '-';

View file

@ -30,16 +30,21 @@ test ()
puts ("\n"); puts ("\n");
puts ("t: itoa (33) == \"33\"\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"); 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"); 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"); puts ("strcmp (itoa (1), \"1\")\n");
if (strcmp (itoa (1), "1")) return 1; if (strcmp (itoa (1), "1"))
return 4;
return 0; return 0;
} }