galinette
galinette

Reputation: 9292

Wrong vsnprintf output

I have the following functions:

void raiseError(const char *msg, ...)
{
    va_list ap;
    va_start(ap, msg); // use variable arg list

    int size = vsnprintf(nullptr, 0, msg, ap);
    std::vector<char> s(size+1, 0);
    vsnprintf(s.data(), size, msg, ap);
    va_end(ap);
    errorString = std::string(s.data()));
}

When I call

raiseError("File not found in <%s> : <%s>", "a", "b" );

The first vsnprintf call (which computes the final string size) returns the correct value of 27. But the final string is:

"File not found in <**A*> :"

Where the '*' characters are random across program launches.

Also, the program works in MinGW, the issue is only seen with linux gcc.

What is wrong in my code?

Upvotes: 4

Views: 920

Answers (1)

Anon Mail
Anon Mail

Reputation: 4770

You can't use ap more than once. Look into using va_copy.

Upvotes: 6

Related Questions