8

This blog post claims that passing a va_list to another function like in the following code is unsafe, and that the va_list must first be copied using va_copy:

void
foo_ap(const char *fmt, va_list ap)
{
    char buf[128];

    vsnprintf(buf, sizeof(buf), fmt, ap);

    // now, do something with buf ...
}

Like one of the comments to the blog post mentions, I can't see how this would be unsafe, as the C99 spec states (7.15):

The object ap may be passed as an argument to another function; if that function invokes the va_arg macro with parameter ap, the value of ap in the calling function is indeterminate and shall be passed to the va_end macro prior to any further reference to ap.

(As long as foo_ap doesn't reference ap after passing it on, the second part of the sentence doesn't seem to apply anyway.) The author of the blog post says in another comment that he might be wrong, but maybe someone can add some clarification. Do I really have to use va_copy to be on the safe side? Or are there any platforms that don't conform to the spec and require the use of va_copy?

3
  • 3
    The blog post seems to directly contradict the clause you cited from the C99 standard. The blog author does say "A long time ago" at the start of it, so my guess is that he was dealing with some old, non-standards-conformant system. Nov 16, 2014 at 3:15
  • 4
    You only need va_copy if you still plan to use ap after vsnprintf returns. For example, you might want to call vsnprintf twice - once to determined the required buffer size, and again to format for real. If you don't need to use ap again except for passing it to va_end, then you don't need to va_copy it. Nov 16, 2014 at 4:44
  • @IgorTandetnik If you make your comment an answer, I'll accept it.
    – nwellnhof
    Dec 31, 2014 at 13:26

1 Answer 1

8

You only need va_copy if you still plan to use ap after vsnprintf returns. For example, you might want to call vsnprintf twice - once to determine the required buffer size, and again to format for real. If you don't need to use ap again (except perhaps for passing it to va_end, if you were the one creating it with va_start), then you don't need to va_copy it.

1
  • 1
    I've observed implementations where a va_list behaves as though passed by value [so arguments consumed by a function that receives it come back into existence when that function returns], and others where it behaves as though passed by reference [the arguments remain consumed]. Problems with using a va_list after calling a method which also uses it are thus not merely "theoretical".
    – supercat
    Jan 4, 2015 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.