Invalid 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 calculates the final string size) returns the correct value 27. But the final string:

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

Where the characters '*' are random during program startup.

In addition, the program works in MinGW, the problem is visible only with linux gcc.

What is wrong in my code?

+4
source share
1 answer

You cannot use ap more than once. Take a look at using va_copy.

+5
source

Source: https://habr.com/ru/post/1613687/


All Articles