HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcMinor

Convert an `int` to a C string with size limitation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertsizewithlimitationintstring

Problem

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 
#include 
#include 

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 = &buf[sizeof buf - 1];
    // Work with negative absolute value to cope with INT_MIN
    int xna = x  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.

Solution

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 < 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.

Code Snippets

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

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

Context

StackExchange Code Review Q#66684, answer score: 6

Revisions (0)

No revisions yet.