GCC 11.2.1 vsnprintf Incorrectly Parses Format Strings Causing Unexpected Behavior
#include <iostream>
#include <cstdio>
#include <cstdarg>
int faulty_vsnprintf(char *str, size_t size, const char *format, ...) {
va_list args;
va_start(args, format);
int result = vsnprintf(str, size, format, args);
va_end(args);
return result;
}
int main() {
const int BUFFER_SIZE = 100;
char buffer[BUFFER_SIZE];
const char* faulty_format = "<= %12ld %20ld %16ld 100%\n";
int result = faulty_vsnprintf(buffer, BUFFER_SIZE, faulty_format, 1, 1, 1);
if (result < 0) {
std::cout << "vsnprintf returned -1 as expected due to an error." << std::endl;
} else {
std::cout << "vsnprintf executed normally, returned: " << result << std::endl;
std::cout << "Buffer content: " << buffer << std::endl;
}
return 0;
}
I am currently working in an Alpine 3.16 environment and using the GCC compiler version g++ (Alpine 11.2.1_git20220219) 11.2.1 dated 20220219. I have encountered an issue where the vsnprintf function returns -1. Upon investigation, it appears that the issue is caused by the misinterpretation of the last % character in the format string, which is erroneously recognized as a format specifier.