Martin Schlott
Martin Schlott

Reputation: 4557

vsnprintf problems with variable arguments

The following code will give the expected result on Visual Studio 2012 but not on XCode 5.0 . What do I miss?

static std::string format(const std::string fmt, ...)
{
    va_list vl;
    va_start(vl, fmt);
    int size=vsnprintf(0, 0, fmt.c_str(), vl);

    if(size<1)
        return std::string();


    char szBuf[256];

    vsnprintf(szBuf, 256, fmt.c_str(), vl);

    return szBuf;
}

The call:

for(int no=1;no<10;no++)
{
    std::string strPath=format("entry%02d.txt",no);
}

will result in correct "entry01.txt" on Windows but it is "entry1852125044.txt" on OSX with XCode.

The above code is shorten to focus on the problem. That is the reason for looking odd (asking for size and not use it). Also I need to process format strings.

Upvotes: 0

Views: 1353

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254631

You are trying to iterate over the va_list twice, once for each call to vsnprintf. You need to bracket each iteration in a va_start/va_end pair:

//...
va_start(vl, fmt);
int size=vsnprintf(0, 0, fmt.c_str(), vl);
va_end(v1);

//...

va_start(vl, fmt);
vsnprintf(szBuf, 256, fmt.c_str(), vl);
va_end(vl);

Upvotes: 7

Related Questions