...
Anchor | ||||
---|---|---|---|---|
|
Noncompliant Code Example (multiple argument evaluation)
The most severe problem with unsafe function-like macros is side effects of macro arguments, as shown in this noncompliant code example.
...
Anchor | ||||
---|---|---|---|---|
|
Compliant Solution (inline function)
A possible and preferable compliant solution is to define an inline function with equivalent but safe semantics:
...
Anchor | ||||
---|---|---|---|---|
|
Compliant Solution (language extension)
Some implementations provide language extensions that make it possible to define safe function-like macros such as the macro ABS()
above that would otherwise require evaluating their arguments more than once. For example, the gcc extension Statements and Declarations in Expressions makes it possible to implement the macro ABS()
in a safe way. Note, however, that since relying on implementation-defined extensions introduces undesirable platform dependencies that may make the resulting code non-portable, such solutions should be avoided in favor of portable ones wherever possible (see MSC14-C. Do not introduce unnecessary platform dependencies).
Code Block | ||
---|---|---|
| ||
#define ABS(x) ({int tmp = (x); tmp < 0 ? -tmp : tmp; }) |
Risk Assessment
Defining an unsafe macro leads invocations of the macro with an argument that has side effects, causing those side effects to occur more than once. This can lead to unexpected or undefined program behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
PRE33 PRE12-C | low | probable | low | P6 | L2 |
Automated Detection
Unknown.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the C++ Secure Coding Standard as PRE12-CPP. Do not define unsafe macros.
References
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. References#ISO/IEC 9899-1999]\] Section 5.1.2.3, "Program execution" |
...