I am trying to recode the itoa function which, given an 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:
"-./,),(-*,(" Which 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 minimum size of the buffer. Using <limits.h> seems to do the trick, but I am not allowed to include headers other than <stdlib.h> and <string.h>. I am also limited to three functions, malloc, free and write. However, I did recode strdup and a lot of functions from the C library.
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 forINT_MIN.
Why?
-2147483648*-1is overflow in 32bit int.2147483647.