va_copy() 应该是 C99 规范的一部分;与所有可变参数一样,支持非常依赖于平台。 va_list、va_copy()、va_start()、va_end() 宏在stdarg.h 中定义。
GCC:当尝试在 GCC 上重用 va_list 时,必须使用 va_copy(),因为 GCC 实现会导致 va_list 被修改,导致指针在 v??printf() 使用后定位在最后一个参数之后功能。
SUN:当尝试在 SunStudio (v11,v12) 中重用 va_list 时,va_list 变量保持不变,可以根据需要多次重用,而无需 va_copy()。
MS_Visual C:不确定,但看起来 2010 VC++ 文档确实提到了“va_copy()”,并且可能暗示重用 va_list 是合理的,但应该进行测试。
例子:
#include <stdio.h>
#include <stdarg.h>
/**
* Version of vsprintf that dynamically resizes the given buffer to avoid overrun.
* Uses va_copy() under GCC compile.
**/
int my_vsprintf(char **buffer, char *msg, va_list args)
{
int bufLen = 0;
va_list dupArgs; // localize args copy
#ifdef __GNUC__
va_copy(dupArgs,args); // Clone arguments for reuse by different call to vsprintf.
#else
dupArgs = args; // Simply ptr copy for GCC compatibility
#endif
// Perform 1st pass to calculate required buffer size. The vsnprintf() funct
// returns the number of chars (excluding \0 term) necessary to produce the output.
// Notice the NULL pointer, and zero length.
bufLen = vsnprintf(NULL,0,msg, dupArgs);
// NOTE: dupArgs on GCC platform is mangled by usage in v*printf() and cannot be reused.
#ifdef __GNUC__
va_end(dupArgs); // cleanup
#endif
*buffer = realloc(*buffer,bufLen + 1); // resize buffer, with \0 term included.
#ifdef __GNUC__
va_copy(dupArgs,args); // Clone arguments for reused by different call to vsprintf.
#endif
// Perform 2nd pass to populate buffer that is sufficient in size,
// with \0 term size included.
bufLen = vsnprintf(buffer, bufLen+1, msg, dupArgs);
// NOTE: dupArgs on GCC platform is mangled by usage in v*printf() and cannot be reused.
#ifdef __GNUC__
va_end(dupArgs); // cleanup
#endif
return(bufLen); // return chars written to buffer.
}
/**
* Version of sprintf that dynamically resizes the given buffer to avoid buffer overrun
* by simply calling my_vsprintf() with the va_list of arguments.
*
* USage:
**/
int my_sprintf(char **buffer, char *msg, ...)
{
int bufLen = 0;
va_list myArgs;
va_start(myArgs, msg); // Initialize myArgs to first variadic parameter.
// re-use function that takes va_list of arguments.
bufLen = my_vsprintf(buffer, msg, myArgs );
va_end(myArgs);
}