No error message when format string is passed as variable to printf functions family
john smith
wempwer@gmail.com
Wed May 13 16:46:00 GMT 2015
The following code falls under UB according to C standard 7.19.6.1 p9
due to usage of "%B" modifier:
"If a conversion specification is invalid, the behavior is undefined."
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
void error(const char *fmt, ...)
{
va_list argp;
fprintf(stderr, "error: ");
va_start(argp, fmt);
vfprintf(stderr, fmt, argp);
vprintf(fmt, argp);
va_end(argp);
fprintf(stderr, "\n");
}
int main(void)
{
error("%d", 2);
printf("%B\n", 2);
exit(0);
}
However, even though there is no requirement imposed on a compiler to
produce error message in UB it's interesting to see that error is only
produced in line 20 where `printf' is used:
c-faq.c:21:2: warning: unknown conversion type character ‘B’ in format
[-Wformat]
There is no error in line 10 and 11:
vfprintf(stderr, fmt, argp);
vprintf(fmt, argp);
Interestingly, if fmt does not come from a variable but is written as
`"%B' an error is produced:
vprintf(fmt, argp); -> vprintf("%B", argp);
warning: unknown conversion type character ‘B’ in format [-Wformat]
At the end of the day, it all comes down to passing format string as
variable - the code below also does not produce error:
const char *str = "Last printf: %B\n";
printf(str, 2);
Can someone explain why this happens?
More information about the Gcc-help
mailing list