I have some C code with a %n
printf:
#include <stdio.h>
int main(){
int i, j;
i = printf( "something%n", &j );
return i + j;
}
There is no error in compilation and execution. printf
prints the string "something".
Why my printf returns -1 and why it doesn't save the n parameter in j?
Here a photo while debugging..
If you are using the Microsoft C compiler and running your program on Windows, then by default, using %n with printf will indeed fail. This is because Microsoft views %n as a security risk and disables it by default in printf and related print formatting functions.
To enable %n add the following line early on in your program:
_set_printf_count_output(1);
This is documented in the important note on %n in the following help article:
Format specification syntax: printf and wprintf functions https://docs.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions
I compiled your code and verified, you can check it here: https://onlinegdb.com/BJIF5EUOI
Result:
Seems it works fine according to documentation ( http://www.cplusplus.com/reference/cstdio/printf/ )
printf
returned total number of characters written, result stored at i
variable
%n
stored number of characters written so far under j
main()
returned i + j
- so 2x total number of characters written
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.