Please, look at the following code that just convert an unsigned int to a string (there may be some unhandled cases but it's not my question), allocating a char array in the heap and returning it, leaving the user the responsibility to free it after the use. Can you explain me why such function (and others similar) do not exist in C standard library? Yes, printf("%s\n", itos(5))
is a memory leak, but this programming pattern is already used and is consider a good practice[1]. IMO, if such functions had existed since the dawn of C we would had little memory leaks more but tons of buffer overflows less!
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char* itos(unsigned int value)
{
int string_l = (value == 0) ? 1 : (int)log10(value) + 1;
char *string = malloc((string_l + 1) * sizeof(char));
int residual = value;
int it;
for (it = string_l - 1; it >= 0; it--) {
int digit;
digit = residual % 10;
residual = residual / 10;
string[it] = '0' + digit;
}
string[string_l] = '\0';
return string;
}
int main(void)
{
char* string = itos(534534345);
printf("%s\n", string);
free(string);
return 0;
}
[1] http://www.opengroup.org/onlinepubs/009695399/functions/getaddrinfo.html
EDIT:
WTH! Habbie did it!
char *string;
asprintf(&string, "%d", 155);
printf("%s\n", string);
free(string);
That's the answer! There's still hope in C! :D
Thanks Habbie!