maverick maverick - 1 year ago 101
C Question

Use of %n more than once in a format string does not seem to work

I am trying to make sure I understand how %n is used, and I have the very simple code below

#include <stdio.h>
int main (void)
int c1, c2;
printf("This%n is fun%n\n", &c1, &c2);

It should print "This is fun" and store the number of characters printed in c1 and c2. But all I get as an output is the string "This". I am using MinGw v 4.9.3 to compile this on Windows10.

a3f a3f
Answer Source

Your program is crashing after printing This.

MinGW uses Microsoft's Visual C++ runtime by default. MSDN says following about "%n":

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.

The default invalid parameter handler aborts your program. Either enable via _set_printf_count_output(1) or compile with -D__USE_MINGW_ANSI_STDIO=1 to use it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download