Wrong type of arguments to formatting function¶
ID: cpp/wrong-type-format-argument
Kind: problem
Security severity: 7.5
Severity: error
Precision: high
Tags:
- reliability
- correctness
- security
- external/cwe/cwe-686
Query suites:
- cpp-code-scanning.qls
- cpp-security-extended.qls
- cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
Each call to the printf
function or a related function should include the type and sequence of arguments defined by the format. If the function is passed arguments of a different type or in a different sequence then the arguments are reinterpreted to fit the type and sequence expected, resulting in unpredictable behavior.
Recommendation¶
Review the format and arguments expected by the highlighted function calls. Update either the format or the arguments so that the expected type and sequence of arguments are passed to the function.
Example¶
In the following example, the wrong format specifier is given for an integer format argument:
int main() {
printf("%s\n", 42); // BAD: printf will treat 42 as a char*, will most likely segfault
return 0;
}
The corrected version uses %i
as the format specifier for the integer format argument:
int main() {
printf("%i\n", 42); // GOOD: printf will treat 42 as an int
return 0;
}
References¶
Microsoft Learn: Format specification syntax: printf and wprintf functions.
CERT C Coding Standard: FIO47-C. Use valid format strings.
Common Weakness Enumeration: CWE-686.