Live data from Hacker News

Generalizing Printf in C

webb.is-a.dev

11–13 of 13 posts

Re: Generalizing Printf in C

#11
post #2

On GNU systems, if you want to generalize printf, all you need is vfprintf - because there is: "fmemopen(3)" that creates FILE* that writes to pre-allocate dbuffer "open_memstream(3)" that creates FILE* that writes to auto-allocated buffer; and if that's not sufficient, there is "fopencookie(3)" which takes general callbacks and creates FILE* that redirects all operations to those callbacks. If that does not work for…

fmemopen and open_memstream are both part of POSIX, so they're not restricted to GNU systems and can be used portably. fopencookie is a GNU extension, though.

Re: Generalizing Printf in C

#12

sprintf can be safely used. - For some conversions, you can establish an upper bound on how many characters they will produce. E.g. a positive decimal integer not more than 9999 does not consume more than four characters. - It's possible to specify truncation. e.g. "%.64s" prints at most 64 characters from the string argument. - There are enirely static cases that can be worked out at compile time, e.g. char big_enuf…

If you really hit the pathological edge case of needed sprintf at runtime with runtime-only buffer sizes, you can still work out the size safely, albeit slowly.

I've done it to make a "safe" sprintf function that allocates the destination buffer, so that the caller cannot overrun it: https://github.com/lelanthran/libds/blob/56d6e18c8970b84c9fa...

Re: Generalizing Printf in C

#13

sprintf can be safely used. - For some conversions, you can establish an upper bound on how many characters they will produce. E.g. a positive decimal integer not more than 9999 does not consume more than four characters. - It's possible to specify truncation. e.g. "%.64s" prints at most 64 characters from the string argument. - There are enirely static cases that can be worked out at compile time, e.g. char big_enuf…

If you really hit the pathological edge case of needed sprintf at runtime with runtime-only buffer sizes, you can still work out the size safely, albeit slowly. I've done it to make a "safe" sprintf function that allocates the destination buffer, so that the caller cannot overrun it: https://github.com/lelanthran/libds/blob/56d6e18c8970b84c9fa...

btw, what you did is called "asprintf" in many stdlibs
Post reply on HN