How to Use Snprintf

bernsteinbear.com

52 points by surprisetalk 5 days ago


st_goliath - 2 days ago

There are `asprintf` and `vasprintf` (takes a va_list argument). Those allocate a sufficiently sized buffer that can be released with `free`.

Yes, it's a GNU extension, but it's also supported by various BSDs [1][2][3], and yes, Musl has it too. It's present in pretty much any sane C library.

[1] https://man.openbsd.org/man3/printf.3

[2] https://man.netbsd.org/vasprintf.3

[3] https://man.freebsd.org/cgi/man.cgi?query=vasprintf&sektion=...

jeroenhd - 2 days ago

That little-known feature turns out to be crucial if you're not careful. printf returns how many bytes were printed. snprintf returns how many bytes would have been printed had the buffer been large enough. Useful for sizing your buffer, but making it a dangerous printf replacement if you don't know the difference.

Cisco and many of Ciscro's customers found out the hard way (during CitrixBleed, https://www.assetnote.io/resources/research/citrix-bleed-lea...), leaking random blocks of memory in the proprietary, C-based web server of their security appliance that gets compromised every now and then.

hdjrudni - 4 days ago

This sentence is confusing:

> 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 'size' includes the null byte, why do we have to add 1?

RhysU - 2 days ago

Once I hacked up an snprintf wrapper that automated any required realloc calls:

https://github.com/RhysU/snprintf_realloc/blob/master/snprin...

Worth critically reviewing before using. It's been a while.