Re: [PATCH] perf: Incorrect use of snprintf results in SEGV

Nick Bowler
2012-03-07T18:45:33Z

On 2012-03-06 19:29 -0600, Peter Seebach wrote:
> To frame it another way: Imagine an alternative function, called
> slenprintf(), which is just like snprintf except that it returns the
> number of bytes written instead of the number it would have liked to
> write in the event that the buffer isn't big enough. And also
> vslenprintf(), analogous to vsnprintf().
>
> Now consider what happens if you have one and want the semantics of the
> other:
[...]
> size_t
> mysnprintf(char *buffer, size_t len, char *fmt, ...) {
> size_t ret;
> va_list ap;
> va_start(ap, fmt)
> ret = vslenprintf(buffer, len, fmt, ap);
> /* now what? */

To answer the question, one "solution" here is to run in a loop
allocating larger and larger buffers until ret is strictly less
than len, then (for this function) free the allocated buffer.

There are a couple functions in POSIX that work this way (*cough*
readlink *cough*), and it's *ugly*.

Cheers,
--
Nick Bowler, Elliptic Technologies (http://www.elliptictech.com/)