Convert an `int` to a C string with size limitation Creating a textual version of an int to save as a C string to a buffer that is all ready allocated and maximum allowable size is determined seems common.  Thought I'd make a function to fulfill that.

If the destination size is too small or destination is NULL, return NULL.

Your critique of functionality, style, use, etc. is requested.

#include &lt;stdlib.h&gt;
#include &lt;limits.h&gt;
#include &lt;string.h&gt;

char *int_strnull(int x, char *dest, size_t dest_size) {
  if (dest != NULL) {
    // Size local buffer to x needs.  Note 10/33 just greater than log(2)
    char buf[sizeof x * CHAR_BIT * 10 / 33 + 3];
    char *p = &amp;buf[sizeof buf - 1];
    // Work with negative absolute value to cope with INT_MIN
    int xna = x &lt; 0 ? x : -x;

    // Form string
    *p = '\0';
    do {
      *--p = '0' - xna % 10;
      xna /= 10;
    } while (xna);
    if (x &lt; 0) {
      *--p = '-';
    }

    // Copy string
    size_t src_size = &amp;buf[sizeof buf] - p;
    if (src_size &gt; dest_size) {
      // Not enough room
      return NULL;
    }
    memcpy(dest, p, src_size);
  }
  return dest;
}


Similar to snprintf(buf, sizeof buf, "%d", some_int); but without the printf() overhead.
Use some constants:

This char buf[sizeof x * CHAR_BIT * 10 / 33 + 3];

Would be a lot better if written like this: char buf[MAX_CONV_CHARS]; (or any other name your might prefer for the constant).

Also, do you really care about being that exact with the size of buf? I usually just throw some large number that can't overflow, like 128.

Return early:

Instead of nesting the entire function under an if, return early:

char *int_strnull(int x, char *dest, size_t dest_size) {

    if ((dest == NULL) || (dest_size &lt; MIN_SIZE)) {
        return NULL;
    }


Mind your naming:

xna is an abbreviation for what exactly? Not obvious to me. x is also very vague. Call it input, number or even value.

int_strnull() also seems odd. Why not just int_to_string()?

Local buffer actually needed?

Finally, I don't really get the necessity of the local buffer buf. Why not simply write to dest directly. That would also save a memcpy at the end. I guess you did that to first figure out the total length of the string. But since it is such a small string, I would suggest just requiring that the output buffer be at least the maximum size.