Why does printf specifier format %n not work?

后端 未结 1 1330
天命终不由人
天命终不由人 2020-12-18 06:32

This is my code:

#include 

int main(void) {
    int n;

    fprintf(stdout, \"Hello%n World\\n\", &n);
    fprintf(stdout, \"n: %d\\n\",          


        
相关标签:
1条回答
  • 2020-12-18 07:14

    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
    
    0 讨论(0)
提交回复
热议问题