New 'n' Improved comp.lang.c FAQ List

Paul De Bra debra at wsinis03.info.win.tue.nl
Wed Apr 3 20:46:03 AEST 1991


In article <3739 at jethro.Corp.Sun.COM> fguille at France.Sun.COM writes:
>bls at u02.svl.cdc.com (Brian Scearce) writes:
>            char *itoa(int i)
>              {
>                static char retbuf[5];         /* biggest int: 32768 */
>                sprintf(retbuf, "%d", i);
>                return retbuf;
>              }
>Should'nt the *really really correct* version allocate an extra character
>in the retbuf array for the end of string delimiter \0 ???

Actually, this version of itoa is wrong for 2 reasons:
- retbuf should have size 7, to account for negative ints as well as the
  terminating null character.
- this version of itoa will not work as expected in a call like:
  printf("%s %s\n",itoa(2),itoa(3));
  the only way to do it right is to allocate memory for the buffer on each
  call. but then, freeing that memory becomes a problem as it cannot be done
  inside itoa...

Paul.
(debra at win.tue.nl)



More information about the Comp.lang.c mailing list