George V. Reilly

Printf %n

In my post about Printf Tricks a couple of years ago, I mentioned that "%n is dangerous and disabled by default in Visual Studio 2005."

I got email today from someone who was porting a large codebase to VS 2005. He was getting an assert from %n and he needed a way to get past it. He intends to fix the uses of %n when he has a chance.

I spent several minutes digging around in MSDN and came up with set_print­f_­coun­t_out­put. Wikipedi­a's Format string attack page led me to Exploiting Format String Vul­ner­a­bil­i­ties, which describes in detail how %n (and %s) may be exploited.

In short, if you continue.

Printf Tricks

It may be old-fashioned, but I still find printf (and sprintf and _vsnprintf) incredibly useful, both for printing debug output and for generating formatted strings.

Here are a few lesser-known formats that I use again and again. See MSDN for the full reference.

%04x - 4-digit hex number with leading zeroes

A quick review of some of the basics.

%x prints an int in hexa­dec­i­mal.

%4x prints a hex int, right-justified to 4 places. If it's less than 4 digits, it's preceded by spaces. If it's more than 4 digits, you get the full number.

%04x prints a hex int, right-justified to 4 places. If it's less than 4 digits, it's preceded continue.