On Unix (Clang 3.8.1), this code outputs:
6: 32
8: a8e
On Windows (MSVC 19.00.24215.1), this code outputs:
6: 12345
6: a12345e
#include <iostream>
#include <stdarg.h>
static std::string getFormattedString(const char* fmt, va_list ap) {
int count = vsnprintf(NULL, 0, fmt, ap) + 1;
std::cout << count << ": ";
if (count <= 0) { return "unable to format message"; }
std::string result = std::string(count, '');
if (vsnprintf(&result[0], count, fmt, ap) < 0) { return "error";}
return result;
}
static std::string getFormattedString(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
std::string result = getFormattedString(fmt, ap);
va_end(ap);
return result;
}
int main(int argc, char *argv[]) {
std::cout << getFormattedString("%d", 12345).c_str() << "
";
std::cout << getFormattedString("a%de", 12345).c_str() << "
";
return 0;
}
Interestingly, they both get the correct count, but on my Linux and OS X machines, this code outputs an incorrect result. What's causing this? Have I incurred UB somewhere?
question from:
https://stackoverflow.com/questions/65879007/issue-with-vsnprintf-in-linux 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…