I am trying to recode the itoa function which, given a int, will return a string representing its decimal value. So far, the functions works well:
char *ft_itoa(int n)
{
char s[1024];
int i;
int neg;
i = 0;
neg = 0;
if (n == 0)
s[i++] = '0';
if (n < 0)
{
n = n * (-1);
neg = 1;
}
while (n != 0)
{
s[i++] = (n % 10) + 48;
n /= 10;
}
if (neg)
s[i++] = '-';
s[i] = '\0';
return (ft_strrev(s));
}
Except for the minimum int value, -2147483648. In that case, the function returns:
"-./,),(-*,("
Wich is... weird. Note that ft_strrev will reverse the result and malloc it. Any clues?
EDIT:
There are quite interesting answers here. I am specially interested in the minium size of the buffer. Using limits.h seems to do the trick, but I am not allowed to include other headers than stdlib.h and string.h. I am also limited in three functions, malloc, free and write. However, I did recode strdup and a lot of functions from libc.
Could someone explain why that line would declare the exact amount of memory I need:
char buf[sizeof(int) * CHAR_BIT / 3 + 3];
Also,
Using unsigned to compute the digits would avoid the problem with INT_MIN. Bug fix for INT_MIN.
Why?