Format String Attacks: How Printf Vulnerabilities Enable Memory Exploitation
May 14, 2026
Format String Attacks exploit C/C++ formatting functions (printf, fprintf, sprintf, syslog) when user-controlled data is passed directly as the format string parameter. Attackers inject format specifiers to read memory, disclose stack data, or write arbitrary values — potentially achieving full code execution.
Dangerous Format Specifiers
| Specifier | Attack Effect |
|---|---|
| %x | Reads and displays a word from the stack (memory disclosure) |
| %s | Reads character strings from arbitrary memory addresses |
| %n | Writes byte count to an int* argument — enables arbitrary memory writes |
| %p | Prints pointer values (address space disclosure) |
The Fundamental Programming Error
// SAFE:printf("%s", str);// VULNERABLE — user-controlled str parsed as format string:printf(str);// If str = "%x %x %x" → stack values leaked to attacker
Prevention Guidance
- Always use an explicit format string:
printf("%s", str)— neverprintf(str). - Avoid the
%nspecifier entirely in production code. - Enable compiler-level warnings:
-Wformat-securityin GCC. - Restrict format strings to static compile-time values where possible.