...
Each conversion specification is introduced by the %
character followed (in order) by
- zero Zero or more flags (in any order), which modify the meaning of the conversion specification
- an An optional minimum field width
- an An optional precision that gives the minimum number of digits to appear for certain conversion specifiers
- an An optional length modifier that specifies the size of the argument
- a A conversion specifier character that indicates the type of conversion to be applied
Common mistakes in creating format strings include
- providing Providing insufficient arguments for the format string
- using Using invalid conversion specifiers
- using Using a flag character that is incompatible with the conversion specifier
- using Using a length modifier that is incompatible with the conversion specifier
- mismatching Mismatching the argument type and conversion specifier
- using Using an argument of type other than
int
for width or precision
...
Conversion |
|
|
|
|
|
|
|
|
|
|
|
|
| Argument |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
|
|
|
|
|
|
| signed Signed integer | |||||
|
|
|
|
|
|
|
|
| unsigned Unsigned integer | |||||
|
|
|
|
|
|
|
|
| unsigned Unsigned integer | |||||
|
|
|
|
|
|
|
|
| unsigned Unsigned integer | |||||
|
|
|
|
|
|
|
|
| unsigned Unsigned integer | |||||
|
| N/E | N/E |
|
| |||||||||
|
| N/E | N/E |
|
| |||||||||
|
| N/E | N/E |
|
| |||||||||
|
| N/E | N/E |
|
| |||||||||
|
|
|
| |||||||||||
|
| NTWS | NTBS or NTWS | |||||||||||
|
|
| ||||||||||||
|
|
|
|
|
|
|
|
| pointer Pointer to integer | |||||
|
|
| ||||||||||||
|
| NTWS | ||||||||||||
|
| noneNone |
Legend:
- SPACE—the space (
" "
) character - N/E—No —no effect
- NTBS—
char*
argument pointing to a null-terminated byte string - NTWS—
wchar_t*
argument pointing to a null-terminated wide character string - XSI—ISO/IEC 9945-2003 XSI extension
...
This compliant solution ensures that the format arguments match their respective format specifications.:
Code Block | ||||
---|---|---|---|---|
| ||||
const char *error_msg = "Resource not available to user."; int error_type = 3; /* ... */ printf("Error (type %d): %s\n", error_type, error_msg); |
...
In this compliant solution, the field width and precision arguments to printf()
format directives are of type int
.:
Code Block | ||||
---|---|---|---|---|
| ||||
int print_int(int i, int width, int prec) { int n; n = printf("%*.*d", width, prec, i); return n; } |
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
GCC |
|
| Can detect violations of this recommendation when the | ||||||
| SV.FMT_STR |
| |||||||
| 486 S | Fully implemented. | |||||||
PRQA QA-C |
| 0179 (U) | Partially implemented. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...