Reusing va_list

I need to make two (or more) passes over va_list. I have a buffer of some size and I want to write a formatted string using sprintf. If the formatted string does not fit in the allocated space, I want to double the selected space and repeat until it fits.

(As a note, I would like to first calculate the length of the formatted string and allocate enough space, but the only function I found can do _snprintf, and it is deprecated in VS2005 ...)

Now there is still no problem: I use vsnprintfand call va_startbefore each involution.

But I also created a function that takes va_listas a parameter, not "...". Then I can not use va_startagain! I read about va_copy, but it is not supported in VS2005.

So how would you do that?

+5
source share
5 answers

I do not see a portable way (and I think that va_copy was introduced in C99 because there was no portable way to achieve its result in c89). Va_list may be a reference layout type declared as

typedef struct __va_list va_list[1];

(see gmp for another user of this trick) and this explains the many language restrictions around them. BTW, don't forget va_end if portability is important.

, stdard.h , - .

+1

va_copy MSVC , va_copy MSVC:

#define va_copy(d,s) ((d) = (s))

, 'portability', #ifndef va_copy #ifdef _MSC_VER VC.

+5

, va_copy() C99; , . va_list, va_copy(), va_start(), va_end() stdarg.h.

GCC: va_list GCC, va_copy(), GCC va_list, av?? printf() .

SUN: va_list SunStudio (v11, v12) va_list , , va_copy().

MS_Visual C: , , V++ 2010 "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);
} 
+3

, , , - . va_copy, , vc2005, .

, , :

va_copy(d,s) ((d) = (s))

, . , va_copy vc2013, , va_copy :

-, msdn:

void va_copy(
   va_list dest,
   va_list src
); // (ISO C99 and later)

va_copy, msvcr120 ( 7 !):

PUSH EBP
MOV EBP,ESP
MOV EAX,DWORD PTR SS:[EBP+8]  ;get address of dest
MOV ECX,DWORD PTR SS:[EBP+0C] ;get address of src
MOV DWORD PTR DS:[EAX],ECX    ;move address of src to dest
POP EBP
RETN

, , , src va_list dest va_list .

ms vc2005 , :

#if _MSC_VER < 1800 // va_copy is available in vc2013 and onwards
#define va_copy(a,b) (a = b)
#endif
+3

Hmmm, to this question, trying to answer another, I thought that I would update some hard-won wisdom with the age of VS2015.

std :: string and variation patterns

template<typename ... Args>
std::string format(const std::string& fmt, Args ... args)
{
    size_t size = std::snprintf(nullptr, 0, fmt.c_str(), args ...) + 1; // Extra space for '\0'
    char *cbuf = std::make_unique<char[]>(size).get();
    std::snprintf(cbuf, size, fmt.c_str(), args ...);
    return std::string(cbuf, cbuf + size - 1); // We don't want the '\0' inside our string tho
}

// usage:
::OutputDebugStringA(format("0x%012llx", size).c_str());

previous skool update

// The macros defined in STDARG.H conform to the ISO C99 standard; 
// the macros defined in VARARGS.H are deprecated but are retained for 
// backward compatibility with code that was written before the ANSI C89 
// standard.

#include <stdio.h>  
#include <stdarg.h>  

static void TraceA(LPCSTR format, ...) {

    // (*) va_copy makes a copy of a list of arguments in its current state.
    // The src parameter must already be initialized with va_start; it may
    // have been updated with va_arg calls, but must not have been reset 
    // with va_end. The next argument that retrieved by va_arg from dest 
    // is the same as the next argument that retrieved from src.

    // (*) The vsnprintf function returns the number of characters 
    // written, not counting the terminating null character. If the 
    // buffer size specified by count is not sufficiently large to 
    // contain the output specified by format and argptr, the return 
    // value of vsnprintf is the number of characters that would be 
    // written, not counting the null character, if count were 
    // sufficiently large. If the return value is greater than count 
    // - 1, the output has been truncated. A return value of -1 
    // indicates that an encoding error has occurred.

    va_list args, argsCopy;
    va_start(args, format);
    va_copy(argsCopy, args);

    // +1 for trailing \0 +1 for \n
    size_t size = vsnprintf(nullptr, 0, format, args) + 1; 

    va_end(args);

    auto buf = std::make_unique<char[]>(size);

    size_t written = vsnprintf(buf.get(), size, format, argsCopy);
    va_end(args);

    // Do what you will with the result
    char *buffer = buf.get();
}
0
source

All Articles