...
Note also that macro parameters cannot be individually parenthesized when concatenating tokens using the ## operator, converting macro parameters to strings using the # operator, or concatenating adjacent string literals. This is an exception, PRE01-C-EX2, to PRE01-C. Use parentheses within macros around parameter names.
...
The macro invocation xstr(foo) expands to 4 because s is stringified when it is used in str(), so it is not macro expanded first. However, s is an ordinary argument to xstr(), so it is completely macro expanded before xstr() is expanded. Consequently, by the time str() gets to its argument, it has already been macro expanded.
Risk Assessment
Recommendation | Severity | Likelihood | Detectable |
|---|
Repairable | Priority | Level | |
|---|---|---|---|
PRE05-C | Low | Unlikely | No |
Yes | P2 | L3 |
Automated Detection
| Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Axivion Bauhaus Suite |
| CertC-PRE05 | |||||||
| CodeSonar |
| LANG.PREPROC.HASH | Macro uses # operator Macro argument is both mixed and expanded Macro |
| uses ## operator | |||||||||
| Helix QAC |
| C0341, C0342, C0801, C0802, C0803, C0811, C0872, C0880, C0881, C0884 | |||||||
| Klocwork |
| MISRA.DEFINE.SHARP.ORDER.2012 | |||||||
| LDRA tool suite |
| 76 S, 125 S, 637 S | Enhanced Enforcement |
| Polyspace Bug Finder |
|
341
0342
0801
0802
803
0811
0872
0880
0881
0884
| Checks for incorrectly expanded macros | ||||||||
| PC-lint Plus |
| 9024 | Assistance provided: reports any use of pasting or stringizing operators in a macro definition |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
| SEI CERT C++ Coding Standard | VOID PRE05-CPP. Understand macro replacement when concatenating tokens or performing stringification |
Bibliography
| [FSF 2005] | Section 3.4, "Stringification" Section 3.5, "Concatenation" |
| [Saks 2008] |
...