I want to do something like this:
char sLength[SIZE_T_LEN];
sprintf(sLength, "%zu", strlen(sSomeString));
That is, I want to print in a buffer a value of type size_t
. The question is: what should be the value of SIZE_T_LEN
? The point is to know the minimum size required in order to be sure that an overflow will never occur.
sizeof(size_t) * CHAR_BIT
(from limits.h
) gives the number of bits. For decimal output, use a (rough) lower estimate of 3 (4 for hex) bits per digit to be on the safe side. Don't forget to add 1
for the nul
terminator of a string.
So:
#include <limits.h>
#define SIZE_T_LEN ( (sizeof(size_t) * CHAR_BIT + 2) / 3 + 1 )
This yields a value of type size_t
itself. On typical 8/16/32/64 bit platforms + 2
is not required (the minimum possible size of size_t
is 16 bits). Here the error is already large enough to yield a correctly truncated result.
Note that this gives an upper bound and is fully portable due to the use of CHAR_BIT
. To get an exact value, you have to use log10(SIZE_MAX)
(see JohnBollinger's answer for this). But that yields a float and might be calculated at run-time, while the version above is compile-time evaluated (and likely costs more stack than the rough estimate already). Unless you have a very RAM constrained system, that is ok. And on such a system, you should refrain from using stdio
anyway.
To be absolutely on the safe side, you might want to use snprintf
(but that is not necessary).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With