Note that there are some explanatory texts on larger screens.

plurals
  1. POInteger to string in C without preallocated char array
    primarykey
    data
    text
    <p>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, <code>printf("%s\n", itos(5))</code> 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 <strong>tons</strong> of buffer overflows less!</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; 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 &gt;= 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; } </code></pre> <p>[1] <a href="http://www.opengroup.org/onlinepubs/009695399/functions/getaddrinfo.html" rel="nofollow noreferrer">http://www.opengroup.org/onlinepubs/009695399/functions/getaddrinfo.html</a></p> <p>EDIT:</p> <p>Habbie's answer:</p> <pre><code>char *string; asprintf(&amp;string, "%d", 155); printf("%s\n", string); free(string); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload