How to use snprintf

August 9, 2025

The sprintf family of functions (sprintf, snprintf, vsnprintf, …) have this little-known feature to what size your buffer should be. In cases where you don’t have a fixed upper bound, this is really useful.

For example:

int size = snprintf(/*str=*/NULL, /*size=*/0,
                    "%d: %s", some_int, some_c_str);
if (size < 0) abort();
int size_with_nul = size + 1;
char *buf = malloc(size_with_nul);
if (buf == NULL) abort();
int result = snprintf(/*str=*/buf, /*size=*/size_with_nul,
                      "%d: %s", some_int, some_c_str);
if (result < 0) abort();

I have size_with_nul because snprintf man pages say

The functions snprintf() and vsnprintf() write at most size bytes (including the terminating null byte (‘\0’)) to str.

If you like, check out this tiny header-only library I wrote a couple of years ago and promptly forgot about.

Go forth and please stop manually computing buffer sizes.