What is the use of the %n
format specifier in C? Could anyone explain with an example?
11 Answers
Most of these answers explain what %n
does (which is to print nothing and to write the number of characters printed thus far to an int
variable), but so far no one has really given an example of what use it has. Here is one:
int n;
printf("%s: %nFoo\n", "hello", &n);
printf("%*sBar\n", n, "");
will print:
hello: Foo
Bar
with Foo and Bar aligned. (It's trivial to do that without using %n
for this particular example, and in general one always could break up that first printf
call:
int n = printf("%s: ", "hello");
printf("Foo\n");
printf("%*sBar\n", n, "");
Whether the slightly added convenience is worth using something esoteric like %n
(and possibly introducing errors) is open to debate.)
-
4Oh my - this is a character-based version of computing the pixel size of string in a given font!– user3458Aug 4, 2010 at 12:41
-
-
12@AndrewS
&n
is a pointer (&
is the address-of operator); a pointer is necessary because C is pass-by-value, and without a pointer,printf
could not modify the value ofn
. The%*s
usage in theprintf
format string prints a%s
specifier (in this case the empty string""
) using a field width ofn
characters. An explanation of basicprintf
principles is basically outside the scope of this question (and answer); I'd recommend reading theprintf
documentation or asking your own separate question on SO. Jan 17, 2014 at 8:59 -
3Thanks for showing a use-case. I don't understand why people just basically copy-paste the manual into SO and reword it sometimes. We're humans and everything is done for a reason which should always be explained in an answer. "Does nothing" is like saying "The word cool means cool" - almost useless knowledge. Jan 25, 2017 at 20:59
-
1@PSkocik It's convoluted and error-prone enough without adding an extra level of indirection. Jun 24, 2019 at 15:22
Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.
#include <stdio.h>
int main()
{
int val;
printf("blah %n blah\n", &val);
printf("val = %d\n", val);
return 0;
}
The previous code prints:
blah blah
val = 5
-
1You mention that the argument must be a pointer to a signed int, then you used an unsigned int in your example (probably just a typo).– btaAug 3, 2010 at 22:21
-
1
-
6
-
1
-
1For some reason the sample raises error with note
n format specifies disabled
. What's the reason?– Johnny_DJul 20, 2014 at 19:46
I haven't really seen many practical real world uses of the %n
specifier, but I remember that it was used in oldschool printf vulnerabilities with a format string attack quite a while back.
Something that went like this
void authorizeUser( char * username, char * password){
...code here setting authorized to false...
printf(username);
if ( authorized ) {
giveControl(username);
}
}
where a malicious user could take advantage of the username parameter getting passed into printf as the format string and use a combination of %d
, %c
or w/e to go through the call stack and then modify the variable authorized to a true value.
Yeah it's an esoteric use, but always useful to know when writing a daemon to avoid security holes? :D
-
2There are more reasons than
%n
to avoid using an unchecked input string as aprintf
format string. Jun 20, 2014 at 0:44
From here we see that it stores the number of characters printed so far.
n
The argument shall be a pointer to an integer into which is written the number of bytes written to the output so far by this call to one of thefprintf()
functions. No argument is converted.
An example usage would be:
int n_chars = 0;
printf("Hello, World%n", &n_chars);
n_chars
would then have a value of 12
.
So far all the answers are about that %n
does, but not why anyone would want it in the first place. I find it's somewhat useful with sprintf
/snprintf
, when you might need to later break up or modify the resulting string, since the value stored is an array index into the resulting string. This application is a lot more useful, however, with sscanf
, especially since functions in the scanf
family don't return the number of chars processed but the number of fields.
Another really hackish use is getting a pseudo-log10 for free at the same time while printing a number as part of another operation.
-
+1 for mentioning uses for
%n
, although I beg to differ about "all the answers...". =P Aug 4, 2010 at 17:25 -
1
-
9@noloader: How so? Use of
%n
has absolutely zero danger of vulnerability to an attacker. The misplaced infamy of%n
really belongs on the stupid practice of passing a message string rather than a format string as the format argument. This situation of course never arises when%n
is actually part of an intentional format string being used. Jul 9, 2013 at 4:06 -
%n allows you to write to memory. I think you are assuming that the attacker does not control that pointer (I could be wrong). If the attacker controls the pointer (it just another parameter to printf), he/she could perform a write of 4 bytes. Whether he/she can profit is a different story.– jwwJul 9, 2013 at 5:00
-
11@noloader: That's true about any use of pointers. Nobody says "bad guys thank you" for writing
*p = f();
. Why should%n
, which is just another way of writing a result to the object pointed to by a pointer, be considered "dangerous", rather than considering the pointer itself dangerous? Jul 9, 2013 at 5:47
The other day I found myself in a situation where %n
would nicely solve my problem. Unlike my earlier answer, in this case, I cannot devise a good alternative.
I have a GUI control that displays some specified text. This control can display part of that text in bold (or in italics, or underlined, etc.), and I can specify which part by specifying starting and ending character indices.
In my case, I am generating the text to the control with snprintf
, and I'd like one of the substitutions to be made bold. Finding the starting and ending indices to this substitution is non-trivial because:
The string contains multiple substitutions, and one of the substitutions is arbitrary, user-specified text. This means that doing a textual search for the substitution I care about is potentially ambiguous.
The format string might be localized, and it might use the
$
POSIX extension for positional format specifiers. Therefore searching the original format string for the format specifiers themselves is non-trivial.The localization aspect also means that I cannot easily break up the format string into multiple calls to
snprintf
.
Therefore the most straightforward way to find the indices around a particular substitution would be to do:
char buf[256];
int start;
int end;
snprintf(buf, sizeof buf,
"blah blah %s %f yada yada %n%s%n yakety yak",
someUserSpecifiedString,
someFloat,
&start, boldString, &end);
control->set_text(buf);
control->set_bold(start, end);
-
I'll give you +1 for the use case. But you are going to fail an audit, so you should probably devise another way to mark the begin and end of the bold text. It seems like three
snprintf
while checking return values will work just fine sincesnprintf
returns the number of characters written. Maybe something like:int begin = snprintf(..., "blah blah %s %f yada yada", ...);
andint end = snprintf(..., "%s", ...);
and then the tail:snprintf(..., "blah blah");
.– jwwJun 10, 2017 at 4:24 -
4@jww The problem with multiple
snprintf
calls is that the substitutions might be rearranged in other locales, so they cannot be broken up like that. Jun 10, 2017 at 6:04 -
Thanks for the example. But couldn't you, like, write an terminal control sequence to make the output bold right before the field and then write a sequence after it? If you don't hardcode the terminal control sequences, you could make them positional (reorderable) too.– PSkocikJun 24, 2019 at 11:08
-
2@PSkocik If you're outputting to a terminal. If you're working with, say, a Win32 rich-edit control, that won't help unless you want to go back and parse the terminal control sequences afterward. That also assumes that you want to honor terminal control sequences in the rest of the substituted text; if you don't, then you'd have to filter or escape those. I'm not saying it's impossible to do without
%n
; I'm claiming that using%n
is more straightforward than alternatives. Jun 24, 2019 at 15:35
The argument associated with the %n
will be treated as an int*
and is filled with the number of total characters printed at that point in the printf
.
It doesn't print anything. It is used to figure out how many characters got printed before %n
appeared in the format string, and output that to the provided int:
#include <stdio.h>
int main(int argc, char* argv[])
{
int resultOfNSpecifier = 0;
_set_printf_count_output(1); /* Required in visual studio */
printf("Some format string%n\n", &resultOfNSpecifier);
printf("Count of chars before the %%n: %d\n", resultOfNSpecifier);
return 0;
}
It will store value of number of characters printed so far in that printf()
function.
Example:
int a;
printf("Hello World %n \n", &a);
printf("Characters printed so far = %d",a);
The output of this program will be
Hello World
Characters printed so far = 12
-
when I try you code it gives me : Hello World Characters printed so far = 36 ,,,,, why 36 ?! I use a 32bit GCC in a windows machine. Oct 25, 2016 at 19:29
Those who want to use %n Format Specifier may want to look at this:
Do Not Use the "%n"
Format String Specifier
In C, use of the "%n" format specification in printf() and sprintf() type functions can change memory values. Inappropriate design/implementation of these formats can lead to a vulnerability generated by changes in memory content. Many format vulnerabilities, particularly those with specifiers other than "%n", lead to traditional failures such as segmentation fault. The "%n" specifier has generated more damaging vulnerabilities. The "%n" vulnerabilities may have secondary impacts, since they can also be a significant consumer of computing and networking resources because large guantities of data may have to be transferred to generate the desired pointer value for the exploit. Avoid using the
"%n"
format specifier. Use other means to accomplish your purpose.
Source: link
-
1
%n is C99, works not with VC++.
-
2
%n
existed in C89. It doesn't work with MSVC because Microsoft disabled it by default for security concerns; you must call_set_printf_count_output
first to enable it. (See Merlyn Morgan-Graham's answer.) Aug 5, 2010 at 5:25 -
No, C89 defines not this feature/backdoorbug. See K&R+ANSI-C amazon.com/Programming-Language-2nd-Brian-Kernighan/dp/… ??where is the URL-tagger for comments?? Aug 5, 2010 at 12:02
-
4You're simply wrong. It's listed plainly in Table B-1 (
printf
conversions) of Appendix B of K&R, 2nd edition. (Page 244 of my copy.) Or see section 7.9.6.1 (page 134) of the ISO C90 specification. Aug 6, 2010 at 8:35 -
-
%n
makesprintf
accidentally Turing-complete and you can e.g. implement Brainfuck in it, see github.com/HexHive/printbf and oilshell.org/blog/2019/02/07.html#appendix-a-minor-sublanguages