This is my implementation of itoa()
(Integer to Alpha), which converts an integer to a string. Memory management and optimization is important. The caller is not responsible for allocation of the string.
The caller is responsible for freeing the string, as my implementation does not allow to call free()
. The function handles everything internally, except freeing. The function allocates memory twice, for the string to be returned and the int array where the digits are stored.
I am concerned about memory leaks with the allocation of the int array which stores the digits. Is there any way to optimize / secure the memory allocation so I do not get leaks?
The code:
#include <stdlib.h>
static int digitcount(int n)
{
int i = 0;
if (n == 0)
return (1);
while (n != 0)
{
n /= 10;
i++;
}
return (i);
}
static int *revarray(int *a, int size)
{
int tmp = 0;
int i = 0;
while (i < size / 2)
{
tmp = a[i];
a[i] = a[size - i - 1];
a[size - i - 1] = tmp;
i++;
}
return (a);
}
static int *getdigits(int n, int size)
{
int *a;
int r = 0;
int i = 0;
a = malloc(size * sizeof(int));
if (a == NULL)
return (NULL);
if (n == 0)
a[i] = 0;
while (n != 0)
{
r = n % 10;
if (r < 0)
r *= -1;
a[i] = r;
i++;
n /= 10;
}
a = revarray(a, size);
return (a);
}
char *itoa(int n)
{
char *nbr;
int *digits;
int digits_size;
int i;
int j;
digits_size = digitcount(n);
digits = getdigits(n, digits_size);
if (n < 0)
digits_size++;
nbr = malloc(digits_size + 1 * sizeof(char));
if (nbr == NULL || digits == NULL)
return (NULL);
i = 0;
j = 0;
if (n < 0)
nbr[i++] = '-';
while (i < digits_size)
{
nbr[i] = digits[j] + '0';
i++;
j++;
}
nbr[i] = 0;
return (nbr);
}
EDIT:
For practice and understanding I wanted to implement my own itoa()
instead of just calling sprintf()
or using external libraries.