Measure before writing
size_t need = snprintf(0, 0, "%zu", number); snprintf writes nothing when its size argument is 0, yet returns the number of characters that would have been written. A bounded call can then format into a suitably sized character array. section 14.1
snprintf formats output into a character array while limiting writes to n bytes. If the return value is at least n, the result was truncated; otherwise the buffer contains a string after a successful call. section 14.1
Use snprintf to:
- Avoid the buffer-overflow vulnerability of sprintf when the output length is unknown. section 14.1
