[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: where the hell is itoa()?



On Sun, Jul 15, 2001, Adi Stav wrote about "Re: where the hell is itoa()?":
> On Sat, Jul 14, 2001 at 10:57:04PM +0300, Ariel Biener wrote:
> > On Sat, 14 Jul 2001, Shaul Karl wrote:
> >     mychar=(char *)calloc(1, sizeof(int));
> 
> Just allocate a long enough string buffer -- char[32] should do it even 
> for long long. sizeof(int) will never be enough.

Actually, the proper way to do this is not to call calloc at all. Using calloc
means the user is forced to "free" the returned pointer, and this might
be a program that deliberately avoids using malloc (e.g., because it is
threaded and malloc needs global mutual exclusion which slows the program
down on an SMP machine). It is also a very inefficient choice in many settings
(e.g., consider a program that needs to output a matrix with a million numbers,
and calls this calloc/free pair a million times).

Instead you should either use a static buffer of length, say, 22 (2+log10(2^64))
characters and return it, or (for threaded programs) ask the user to supply
their own buffer (together with a size parameter!): or have both, in the form
of a itoa and itoa_r calls.


-- 
Nadav Har'El                        |      Sunday, Jul 15 2001, 24 Tammuz 5761
nyh@math.technion.ac.il             |-----------------------------------------
Phone: +972-53-245868, ICQ 13349191 |Birthdays are good for you - the more you
http://nadav.harel.org.il           |have the longer you live.

=================================================================
To unsubscribe, send mail to linux-il-request@linux.org.il with
the word "unsubscribe" in the message body, e.g., run the command
echo unsubscribe | mail linux-il-request@linux.org.il