Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Assertions are a valuable diagnostic tool for finding and eliminating software defects that may result in vulnerabilities. (See guideline recommendation MSC11-C. Incorporate diagnostic tests using assertions.) The runtime assert() macro has some limitations, however, in that it incurs a runtime overhead and , because it calls abort(). Consequently, the runtime assert() macro is only useful for identifying incorrect assumptions and not for runtime error checking. As a result, runtime assertions are generally unsuitable for server programs or embedded systems.

Wiki Markup
Static assertion is a new facility in the C+\+ 0X draft standard \[[Becker 082008|AA. Bibliography#Becker 08]\] and takes the form:

Code Block
static_assert(constant-expression, string-literal);

According to the C++ 0X draft standard, the constant-expression in a static assert declaration is a constant expression that can be converted to bool at compile time. If the value of the converted expression is true, the declaration has no effect. Otherwise, the program is ill-formed, and a diagnostic message (which includes the text of the string-literal) is issued at compile time. For example,

Code Block
/* Passes */
static_assert(
  sizeof(int) <= sizeof(void*), 
  "sizeof(int) <= sizeof(void*)"
); 

/* Fails */
static_assert(
  sizeof(double) <= sizeof(int), 
  "sizeof(double) <= sizeof(int)"
);

...

Wiki Markup
The {{JOIN()}} macro used the {{\##}} operator \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] to concatenate tokens. See recommendation [PRE05-C. Understand macro replacement when concatenating tokens or performing stringification] to understand how macro replacement behaves in C when using the {{\##}} operator.

...

Other uses of static assertion are shown in recommendation STR07-C. Use TR 24731 for remediation of existing string manipulation code and rule FIO35-C. Use feof() and ferror() to detect end-of-file and file errors when sizeof(int) == sizeof(char).

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

C++ Secure Coding Standard: DCL03-CPP. Use a static assertion to test the value of a constant expression

Bibliography

unmigrated-wiki-markup

\[[Becker 2008|AA. Bibliography#Becker 08]\] \[[Eckel 2007|AA. Bibliography#Eckel 07]\] \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 6.10.1, "Conditional inclusion," and Section 6.10.3.3, "The ## operator," and Section 7.2.1, "Program diagnostics"

Bibliography

Wiki Markup
\[[Becker 2008|AA. Bibliography#Becker 08]\] 
\[[Eckel 2007|AA. Bibliography#Eckel 07]\] diagnostics"
\[[Klarer 2004|AA. Bibliography#Klarer 04]\]
\[[Saks 2005|AA. Bibliography#Saks 05]\]
\[[Saks 2008|AA. Bibliography#Saks 08]\]

...