Guessing buffer size needed for sprintf beforehand

Doug Gwyn gwyn at brl-smoke.ARPA
Thu May 19 21:51:01 AEST 1988


In article <13621 at comp.vuw.ac.nz> andrew at comp.vuw.ac.nz (Andrew Vignaux) writes:
>[] CAN you pass va_list's around like this?

Sure.  The only thing you have to be aware of is that va_list may be
an array or some other data type (void * or struct most likely), so you
can't be sure whether it will be passed by reference or not.  Therefore,
after the called function returns, further use of the va_list before
va_end is non-portable.  You could avoid this problem by passing the
ADDRESS of the va_list instead, but older compilers don't understand
& applied to an array name.

>[] Given that you are allowed to pass va_list's around why CAN't you
>   write:
>		va_start (ap);
>		count = count_printf (fmt, ap);
>		rv = vsprintf (new_space, fmt, ap);
>		va_end (ap);
>   (this does not work on pyramids)

Non-portable; see my initial comment.

>		save_ap = ap;
>		i = va_arg (ap, int);
>		j = va_arg (save_ap, int);
>   (this does not work on pyramids)

Non-portable; use memcpy to make the copy.  You should actually use
separate va_start/va_end on each copy of the va_list, to be safe.

>		save_ap = ap;
>		rv = vprintf (fmt, ap);
>		/* now get the parameter after the printf args */
>		i = va_arg (ap, int);
>   (this ONLY works on pyramids-re comment)

Non-portable; see my initial comment.

>[] CAN you strip a few arguments off the va_list and then pass it to other
>   routines?

Sure.

>Presumably there is a more precise definition of the varargs stuff
>somewhere.

There sure is: the forthcoming ANSI/ISO C standard.  We trashed <varargs.h>
in favor of <stdarg.h> as part of allowing a different linkage method to
be used for variadic functions than for normal functions.  Old varargs was
never precisely enough defined, as you have discovered.

>Is there any need for a va_rewind ()?

No.

>[Aside: does va_start have 2 parameters in the new standard? -- boy am I out
>of date :-(]

Yes, one of the parameters provides an "anchor point" in the parameter
list, as required for some implementation methods.  Therefore, variadic
functions must have at least one argument.



More information about the Comp.unix.wizards mailing list