On Thu, Mar 30, 2023 at 08:29:45AM +0000, Qiang Ren via Gcc-bugs wrote: > I found a bug in the result of std::vsnprintf(), here is the test app that > can reproduce it. > I tested with g++ 11.2 and 12.2 and both have the bug, and this issue does > not happen with visual c++.
gcc-bugs is not the right way to report GCC bugs, though in this case the only bug is in your program. You can't use the same va_list multiple times as you pass it to std::vsnprintf, either you need to use va_copy before the first call and use the copy in one of the two calls, or you need to va-end after the first vsnprintf call and va_start again before the second call. > > #include <stdio.h> > #include <string> > #include <iostream> > #include <cstdarg> > > int Sprintf(std::string& s, const char* pszFormat, ...) { > va_list argptr; > va_start(argptr, pszFormat); > > auto n = std::vsnprintf(nullptr, 0, pszFormat, argptr); > char* buf = (char*)malloc(n + 1); > n = std::vsnprintf(buf, n + 1, pszFormat, argptr); > s = buf; > free(buf); > > va_end(argptr); > return n; > } Jakub