Determining sprintf buffer size - what's the standard?

前端 未结 7 1893
臣服心动
臣服心动 2020-11-28 06:51

When converting an int like so:

char a[256];
sprintf(a, \"%d\", 132);

what\'s the best way to determine how large a should be? I a

7条回答
  •  庸人自扰
    2020-11-28 07:22

    If you're printing a simple integer, and nothing else, there's a much simpler way to determine output buffer size. At least computationally simpler, the code is a little obtuse:

    char *text;
    text = malloc(val ? (int)log10((double)abs(val)) + (val < 0) + 2 : 2);
    

    log10(value) returns the number of digits (minus one) required to store a positive nonzero value in base 10. It goes a little off the rails for numbers less than one, so we specify abs(), and code special logic for zero (the ternary operator, test ? truecase : falsecase). Add one for the space to store the sign of a negative number (val < 0), one to make up the difference from log10, and another one for the null terminator (for a grand total of 2), and you've just calculated the exact amount of storage space required for a given number, without calling snprintf() or equivalents twice to get the job done. Plus it uses less memory, generally, than the INT_MAX will require.

    If you need to print a lot of numbers very quickly, though, do bother allocating the INT_MAX buffer and then printing to that repeatedly instead. Less memory thrashing is better.

    Also note that you may not actually need the (double) as opposed to a (float). I didn't bother checking. Casting back and forth like that may also be a problem. YMMV on all that. Works great for me, though.

提交回复
热议问题