1
char buf[10];
int counter, x = 0;
snprintf (buf, sizeof buf , "%.100d%n", x, &counter); 
printf("Counter: %d\n", counter)

I am learning about precision with printf. With %.100d%n, the precision here gives 100 digits for rendering x.

What I don't understand is why would the counter be incremented to 100, although only 10 characters are actually written to the buffer?

Marjan
  • 139
  • 1
  • 1
  • 6
  • 2
    The `100` you're getting is the size that is _actually_ needed to printf the whole thing without truncation. Anyway I'd not use `%n` alltogether (it's not implemented on all platforms), but rather use the return value of `snprintf`. – Jabberwocky Mar 05 '19 at 14:53
  • Take a look at what is actually written to your `buf` – Thomas Jager Mar 05 '19 at 14:54
  • @Jabberwocky %n isn't implemented on windows unless you use `gcc -D__USE_MINGW_ANSI_STDIO=1` – Jean-François Fabre Mar 05 '19 at 14:54
  • 1
    it's the design of %n specifier, which can also be used as a security hole – Jean-François Fabre Mar 05 '19 at 14:54
  • 1
    @Jean-FrançoisFabre `%n` being a security hole [isn't really a strong argument](https://stackoverflow.com/questions/23421115/printf-with-n-raises-fatal-error). See also https://stackoverflow.com/questions/54957216/why-does-printf-specifier-format-n-not-work/54959487#comment96680630_54959487 It seems more like just another Microsoftian non-portable incompatibility. – Andrew Henle Mar 05 '19 at 15:05
  • I didn't mean it like that. Windows printf doesn't support %n because windows native printf sucks. – Jean-François Fabre Mar 05 '19 at 15:14

1 Answers1

1

The ten bytes written to buf are 9 spaces and 1 '\0' (zero terminator), counter is assigned the value 100 for 99 spaces and 1 '0' (digit zero).

   buf <== "         "
%.100d <== "          .....   0"

Note that buf is incomplete: it does not have a '0'.

pmg
  • 106,608
  • 13
  • 126
  • 198