itoa'd you so?

Dave Smith dave at
Fri Sep 21 16:11:44 MDT 2007

Charles Curley wrote:
> Ah, good. Did you finally get around to looking at the solution I
> posted to this thread two days ago?

Yup, it's pretty nice with only a few warts. It doesn't work for zero or 
INT_MIN. It also crashes at random points (sometimes after 6700 
invocations, sometimes after 5001, sometimes after 8105, etc) when run 
in a for loop.

My version skips the strcat() at the end of itoa() in favor of just 
returning a char* that points at where my itoa() put the string in the 
specified buffer. The caller can then know where to find the int. It 
saves a bit of time, but at the slight cost of a somewhat bulky API.

Here's my code:

#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>

// This is a special case. Redefine it for platforms with a different 
value of INT_MIN:
#define INT_MIN_STRING "-2147483648"

// Writes the value in ascii into buf, and returns a pointer inside
// buf where the ascii string begins. The string will be null
// terminated
char* itoa( int value, char *buf, int buflen )
    // Write the number from the end of the buffer, right-to-left:
    int pos = buflen - 1;

    buf[pos--] = '\0';

    // Special case for zero:
    if( value == 0 )
        buf[pos--] = '0';
    // You can't take the absolute value of INT_MIN, because it would be 
too long, and
    // overflow INT_MAX, and result in INT_MIN again, so it's a special 
    else if( value == INT_MIN )
        strcpy( buf, INT_MIN_STRING );
        return buf;
    // Done with special cases. Do the generic case:
        int i = abs( value );

        // Write each 10's place value, starting at the right:
            buf[pos--] = '0' + (i % 10);
        while( i /= 10 );

        // Prepend a negative sign for negative values:
        if( value < 0 )
            buf[pos--] = '-';

    // Return a pointer into the buf where we finished writing
    // the front of the string:
    return &(buf[pos+1]);


More information about the PLUG mailing list