Populating a va_list Populating a va_list c c

Populating a va_list


This is a bad idea because the va_list abstraction is there to hide some grim compiler/architecture specific details regarding stack-pointers and what not. And it is pretty much bound to the function's scope once initialized. If you wind the stack and reference a previous frames va_args out of scope, things can go bad. You can pass them around but ...

expect bugs

See: http://lists.freebsd.org/pipermail/freebsd-amd64/2004-August/001946.html

Also checkout man(3) va_copy and friends for safer handling of va_args and passing them around.

IMHO the va_args stuff is not very neat. In the past I have dealt with this by initializing structures/opaque pointers on the heap then using pointer arithmetic to work the data. But this is a hack and depends on circumstances.


I understand and agree with Aiden's warnings - va_list and friends are dangerous since they hide low-level calling conventions. But ... in this situation I think you have no other option. Put the static ... function into the .c file so nobody else can see it, sort of a proxy to the function you need to call, test the hell out of it, and be done. Just make sure you don't expose the variadic arguments up the call chain.


Your idea of a proxy function that creates the va_list is the right way to do it. There is no need for that proxy to have public scope. However, if you might find that the proxy already exists. For instance, in many library implementations sprintf() is just a proxy for vsprintf().

Unless you are willing to tie your code to a specific compiler and target platform, there is no better way. The names defined in <stdarg.h> are there to provide a portable and consistent interface to support access to variadic argument lists. The only portable way to implement and use variadic functions is through that interface.

That said, it is possible that you could sacrifice portability by duplicating a call frame in an array and hand construct a va_list that correctly references it. The result will never be portable.