[uClibc]Bug Fix: itoa.c

Manuel Novoa III mnovoa3 at bellsouth.net
Fri Dec 15 05:57:04 UTC 2000


Erik,

I found two problems with misc/internal/itoa.c.
1) It only allocated a buffer 7 bytes long (ouch!).
2) It doesn't deal properly with INT_MIN.
Below is a fixed version.  The function is so trivial, I wound up
rewriting it in my coding style.  Object code size does not change
significantly.  In fact, for me it went down from 95 to 92 bytes.

Question:
I think I asked this before, but since itoa is an internal and
nonstandard routine, shouldn't it be called _itoa or __itoa ?
The same question arises for the other routines in misc/internal:
ltoa, ultoa, ltostr, and ultostr.

Here are all the locations were the misc/internal routines occur.
It wouldn't take much to change the names.  In fact, ltoa and ultoa
aren't referenced at all and could be removed.

uClibc/net/addr.c:extern char *itoa(int);
uClibc/net/addr.c:      strcpy(buf, itoa((addr >> 24) & 0xff));
uClibc/net/addr.c:      strcat(buf, itoa((addr >> 16) & 0xff));
uClibc/net/addr.c:      strcat(buf, itoa((addr >> 8) & 0xff));
uClibc/net/addr.c:      strcat(buf, itoa(addr & 0xff));
uClibc/string/strsignal.c:extern char *itoa(int i);
uClibc/string/strsignal.c:      strcat(retbuf, (char *) itoa(sig));
uClibc/string/strerror.c:extern char *itoa(int);
uClibc/string/strerror.c:       strcat(retbuf, (char *) itoa(err));
uClibc/misc/assert/__assert.c:extern char *itoa(int);
uClibc/misc/assert/__assert.c:  errput(itoa(linenumber));
uClibc/stdio/printf.c:  char tmp[64], *ltostr(), *ultostr();
uClibc/stdio/printf.c:              ptmp = ltostr((long) ((lval)
uClibc/stdio/printf.c:              ptmp = ultostr((unsigned long) ((lval)

Thinking about ltoa.c reminded me of something.
Is there any purpose for stdio/dputs.c ?  It doesn't seem to be called
anywhere.

Manuel

---------------------- misc/internal/itoa.c ----------------------
/* itoa.c <ndf at linux.mit.edu> */

/* 
 * Rewritten 12/13/2000 by Manuel Novoa III.
 * Fixed insufficient buffer allocation.
 * Fixed problem handling INT_MIN.
 */

#include <limits.h>

#if INT_MAX > 2147483647
#error need to increase size of buffer
#endif

/* 10 digits + 1 sign + 1 trailing nul */
static char buf[12];

char *itoa(int i)
{
	char *pos = buf + sizeof(buf) - 1;
	unsigned int u;
	int negative = 0;

	if (i < 0) {
		negative = 1;
		u = ((unsigned int)(-(1+i))) + 1;
	} else {
		u = i;
	}

	*pos = 0;

	do {
		*--pos = '0' + (u % 10);
		u /= 10;
	} while (u);

	if (negative) {
		*--pos = '-';
	}

	return pos;
}





More information about the uClibc mailing list