|
From: Per W. <pw...@ia...> - 2003-04-02 01:39:54
|
Assign of string termination will be one position off, i.e. outside your
buffer.
A buffer[MAXSZ] may only access from 0 to MAXSZ-1 and the pointer is
initialized to p[MAXSZ], i.e. first index outside the buffer.
/Per W
On Tue, 1 Apr 2003, Luigi Santillo wrote:
> Hello,
>
> I've revised the previous implementation of "itoa", adding the
> enhancements that Per Westmark suggested. The code lacks error
> checking, so isn't robust at all.
>
> --
> >> gisan >>
>
>
>
> t_itoa.c
> --------
> #include <stdio.h>
> #include "itoa.h"
>
> int
> main()
> {
> int k = 123; /* integer value to be converted */
> char *s = itoa(k); /* string holding the converted value */
>
> printf("INPUT:\tk = %d\n", k);
> printf("OUTPUT:\ts = %s\n\n", s);
>
> k = -4567; /* a little harder: using a negative number */
> s = itoa(k);
> printf("INPUT:\tk = %d\n", k);
> printf("OUTPUT:\ts = %s\n\n", s);
>
> return 0;
> }
> --------
>
>
> itoa.h
> ------
> #ifndef itoa_h
> #define itoa_h
> #pragma defs_in itoa.c /* needed by makefile generator (ignore it) */
>
> /* turn an integer into a string (i.e. an array) */
> char *
> itoa(int n);
>
> #endif /* not itoa_h */
> ------
>
>
> itoa.c
> ------
> #include "itoa.h"
> #define MAXSZ 21 /* assuming integer is made of 19 digits + sign */
>
> char *
> itoa(int n)
> {
> static char buf[MAXSZ];
> char *p = buf + MAXSZ; /* sweep across buffer */
> char neg = 0; /* 1 means that the integer is negative */
>
> if (n < 0) /* negative integer */
> {
> n = -n; /* work on its absolute value */
> neg = 1; /* turn on the flag */
> }
>
> *p = '\0'; /* terminate string */
>
> while (n && p > buf) /* main loop */
> {
> *--p = '0' + n % 10; /* char for a digit as offset from '0' */
> n /= 10; /* drop last character */
> }
>
> if (neg && p > buf ) /* prepend a negative sign */
> *--p = '-';
>
> return p;
> }
> ------
>
>
>
> -------------------------------------------------------
> This SF.net email is sponsored by: ValueWeb:
> Dedicated Hosting for just $79/mo with 500 GB of bandwidth!
> No other company gives more support or power for your dedicated server
> http://click.atdmt.com/AFF/go/sdnxxaff00300020aff/direct/01/
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www.noicys.cjb.net/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|