Is it safe to pass va_list to another function without using va_copy?

This blog post states that passing va_list another function, as in the following code, is unsafe and that va_list needs to 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 ... } 

As in one of the comments on the blog post, I do not see how it will be unsafe, since the specification C99 (7.15):

The ap object can be passed as an argument to another function; if this function calls the va_arg macro with the ap parameter, the ap value in the calling function is undefined and must be passed to the va_end macro before any additional reference to ap .

(As long as foo_ap does not reference ap after passing it, the second part of the sentence does not seem to apply yet). The blog post author says in another comment that he might be wrong, but maybe someone might add some clarification. Do I really have to use va_copy to be safe? Or are there any platforms that do not meet the specification and require the use of va_copy ?

+7
c language-lawyer c99 variadic-functions
source share
1 answer

You only need va_copy if you are still planning on using ap after vsnprintf returns. For example, you can call vsnprintf twice - once to determine the required buffer size, and again to format for real. If you do not need to use ap again (with the possible exception of passing it to va_end , if you created it using va_start ), you do not need va_copy it.

+6
source share

All Articles