As documented in the Microsoft documentation, the %n
is disabled by default in the Microsoft C library used on your MinGW system:
Important
Because the %n
format is inherently insecure, it is disabled by default. If %n
is encountered in a format string, the invalid parameter handler is invoked, as described in Parameter Validation. To enable %n
support, see _set_printf_count_output
.
Whether %n
is actually unsafe as claimed by Microsoft is highly debatable. The examples shown to support this claim combine this printf
function with the use of a variable format string that can by changed by the attacker via a buffer overflow error.
On some Microsoft systems (but maybe not the latest), you could fix your program this way:
#include <stdio.h>
int main(void) {
int n;
_set_printf_count_output(1);
fprintf(stdout, "Hello%n World
", &n);
fprintf(stdout, "n: %d
", n);
return 0;
}
For a more portable approach, here is a work around to avoid using %n
and still get the same results:
#include <stdio.h>
int main(void) {
int n;
n = fprintf(stdout, "Hello");
fprintf(stdout, " World
");
fprintf(stdout, "n: %d
", n);
return 0;
}
Output:
Hello World
n: 5
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…