top | item 23445779

(no title)

yokohummer7 | 5 years ago

> %n takes a pointer and writes (!!) the number of bytes printed so far.

> Okay, everyone probably knows this. Let's get a bit more advanced.

Ok, but I didn't know about that. What's the use?

discuss

order

Someone|5 years ago

One use is aligning outputs:

  char *prefix = "example";
  char *line1 = "line 1";
  char *line2 = "line 2";
  printf("%s: %n%s\n", prefix, &n, line1);
  printf("%*s%s\n", n, "", line2);
will output

  example: line 1
           line 2
That’s a bit more robust than using strlen(s)+2, where you have to keep that magic constant 2 in sync with ": ". Moving ": " to a variable and using strlen(s)+strlen(separator) would fix that, though (at the price of speed, unless you’ve a compiler that optimizes that away)

quietbritishjim|5 years ago

> That’s a bit more robust than using strlen(s)+2

strlen wouldn't even be an option if you were formatting something that's not a string e.g.

    int n;
    int prefix_num = 23;
    char *line1 = "line 1";
    char *line2 = "line 2";
    printf("example %d: %n%s\n", prefix_num, &n, line1);
    printf("%*s%s\n", n, "", line2);

JoshTriplett|5 years ago

This only works if you're not dealing with Unicode, where the number of bytes, the number of characters, and the width of those characters can all vary.

tgv|5 years ago

I'd never heard of %n, but I use printf's return value (the number of bytes written) for this kind of purpose, so

  n = printf("%s: ", prefix);
  printf("%s\n", line1);
  printf("%*s%s\n", n, " ", line2);

zlynx|5 years ago

I seem to recall using it to auto-adjust column widths.

And we did something with it involving string translations. Since we didn't control the translated format string we couldn't just count the characters in the source code.

But it's been a really long time and I don't recall the details.

MertsA|5 years ago

Well the fun use is using it to exploit printf format string vulnerabilities. Microcorruption has a fun level involving that IIRC.

CamperBob2|5 years ago

Normally you'd use %n with input functions like scanf(), not printf().

bawolff|5 years ago

To support format string vulnerabilities! /s