This is my code:
#include
int main(void) {
int n;
fprintf(stdout, \"Hello%n World\\n\", &n);
fprintf(stdout, \"n: %d\\n\",
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", &n);
fprintf(stdout, "n: %d\n", 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\n");
fprintf(stdout, "n: %d\n", n);
return 0;
}
Output:
Hello World
n: 5