...
Code Block |
---|
static_assert(sizeof(int) <= sizeof(long), "sizeof(int) <= sizeof(long)"); /* Passes */ static_assert(sizeof(double) <= sizeof(int), "sizeof(double) <= sizeof(int)"); /* Fails */ |
Non-Compliant Code Example
This non-compliant code uses the assert()
macro to assert a property concerning a memory-mapped structure that is essential for the code that uses this structure to behave correctly.
...
While the use of the runtime assertion is better than nothing, it needs to be placed in a function and executed, typically removed from the actual structure to which it refers. The diagnostic only occurs at runtime, and only if the code path containing the assertion is executed.
Compliant Solution
For assertions involving only constant expressions, some implementations allow the use a preprocessor conditional statement, as in:
...
Unfortunately, this solution is not portable. C99 does not require that implementations support sizeof
, offsetof
or enumeration constants in #if
conditions. According to Section 6.10.1, "Conditional inclusion", all identifiers in the expression that controls conditional inclusion either are, or are not, macro names. Some compilers allow these constructs in conditionals as an extension, but most do not.
Compliant Solution
This compliant solution mimics the behavior of static_assert
in a portable manner.
...
Wiki Markup |
---|
The {{JOIN()}} macro used the {{##}} operator \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] to concatenate tokens. See \[[PRE05-A. Understand macro replacement]] to understand how macro replacement behaves in C when using the {{##}} operator. |
Risk Assessment
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL03-A | 1 (low) | 1 (unlikely) | 1 (high) | P1 | L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.10.1, "Conditional inclusion," and Section 6.10.3.3, "The ## operator" [Klarer 04] R. Klarer, J. Maddock, B. Dawes, and H. Hinnant. "Proposal to Add Static Assertions to the Core Language (Revision 3)" (ISO C++ committee paper ISO/IEC JTC1/SC22/WG21/N1720, October 2004). This document is available online at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1720.html. \[Saks 08] Dan Saks, Stephen C. Dewhurst. Presentation. Sooner Rather Than Later: Static Programming Techniques for C++. \[Saks 05] Dan Saks. [_Catching errors early with compile-time assertions|http://www.embedded.com/columns/programmingpointers/164900888?_requestid=287187]. Embedded Systems Design. June, 2005. \[Eckel 2007] Bruce Eckel. [_Thinking in C++ - Volume 2_|http://bruce-eckel.developpez.com/livres/cpp/ticpp/v2/]. January 25, 2007. |
...