http://ideone.com/ffjDAv

#include <cstdio> char *names = "Windows\0System\0Config\0"; int main() { int l, r; for (char *name=names; *name; name+=r-l+1) if (printf("Folder: %n%s%n\n", &l, name, &(r=0)), !r) break; // Произошла ошибка, вероятно, стоит что-то сделать return 0; } 

It is clear that when feeding printf on user strings as a format, %n can do something wrong. But is there any harm from it in such a code in comparison with the variant in which it is not used?

http://ideone.com/xd5SYu

 #include <cstdio> #include <cstring> char *names = "Windows\0System\0Config\0"; int main() { for (char *name=names; *name; name+=strlen(name)+1) printf("Folder: %s\n", name); return 0; } 

PS: Based on the discussion in another answer .

  • one
    operator comma in if? Well, why write so? - Abyx pm
  • @Abyx, yes, comma. But she certainly is not a security hole :) - Qwertiy
  • And in the minds of readers? :-D - VladD pm
  • one
    For the time being, I found only exploits if the programmer wrote printf(s) , meaning printf("%s", s) . But such a code crashes the program without %n , with only one %s , and is a subscription for brainwashing from the authorities. - VladD
  • one
    IMHO ok. I would only write if without checking r , like so if ((rc = printf(...)) < 0) break; because, as they say in man - If an output error is encountered, a negative value is returned. . / I do not see any holes here. / And the difference between 1) and 2) is the first more efficiently, the work of strlen (almost for nothing?) Is done in printf , but more difficult to understand (however, I personally am 1)). - avp

1 answer 1

If then instead of printf someone writes wprintf , then the first code will break for strings containing national characters.

  • 2
    Please explain in more detail on which platforms \ implementations this happens and why. - Cerbo