To use sprintf, you’d have to guess at the buffer size to pass in, or suffer a buffer overflow.
snprintf is a bit better in that you can recover from passing a buffer that’s too small, but still either requires you to be generous in sizing the buffer, or accept that you often call snprintf twice, doing double work.
The way around that is to pass a pointer to an allocation routine, but that’s a simple form of the allocator interface that this article favors.
This can typically be avoided though. With your sprintf example you could have one function that does the first half that calculates the size and then a second function that does the second half that actually copies into the destination buffer. Alternatively if you want to use realloc you could have a function like snprintf which allows resuming from where it ran out of space.
The second idea is neat though... it could return an extra argument which is a pointer to the first part of the format string that wasn't printed
----
ADDED: I thought charcircuit was talking about always calling two functions in a row, missing the original comment that charcircuit was replying to. My bad, so I'd like to update this comment as follows...
I think the former approach would indeed work if the first call is always given a pointer to the space that can be used to record what has been done so far. Like, `snprintf(ptr, n, &recover, "format", ...)`, and `recover` can be relatively small, like 16 bytes. I would record original `ptr` and `format` arguments to be safe, and largest offsets to `ptr` and `format` that are known to be written and synchronized to each other. Of course this is just a workaround for C's inability to construct and return a sum type.
The caller can allocate memory to be shared between the 2 function calls to avoid needing duplicate work
With the approach of having the caller allocate you have carefully design the API to make it possible.