C99The C Standard, Section 7.2.1.1 [ISO/IEC 9899:2011], defines assert()
to have the following behavior [ISO/IEC 9899:1999]:
The
assert
macro puts diagnostic tests into programs; it expands to a void expression. When it is executed, ifexpression
(which shall have a scalar type) is false (that is, compares equal to 0), theassert
macro writes information about the particular call that failed (including the text of the argument, the name of the source file, the source line number, and the name of the enclosing functionâ”the function—the latter are respectively the values of the pre-processing macros__FILE__
and__LINE__
and of the identifier__func__)
on the standard error stream in an implementation-defined format. It then calls theabort
function.
Because assert()
calls abort()
, cleanup functions registered with atexit()
are not called. If the intention of the programmer is to properly clean up in the case of a failed assertion, then runtime assertions should be replaced with static assertions where possible. (See recommendation DCL03-C. Use a static assertion to test the value of a constant expression.) When the assertion is based on runtime data, the assert
should be replaced with a runtime check that implements the adopted error strategy. (See recommendation ERR00-C. Adopt and implement a consistent and comprehensive error-handling policy.)
See recommendation ERR04-C. Choose an appropriate termination strategy for more information on program termination strategies and recommendation MSC11-C. Incorporate diagnostic tests using assertions for more information on using the assert()
macro.
...
Code Block | ||||
---|---|---|---|---|
| ||||
void cleanup(void) {
/* Delete temporary files, restore consistent state, etc. */
}
int main(void) {
if (atexit(cleanup) != 0) {
/* Handle error */
}
/* ... */
assert(/* something bad didn't happen */);
/* ... */
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
void cleanup(void) { /* delete temporary files, restore consistent state, etc */ } int main(void) { if (atexit(cleanup) != 0) { /* Handle error */ } /* ... */ if (/* something bad happened */) { exit(EXIT_FAILURE); } /* ... */ } |
Risk Assessment
Unsafe usage use of abort()
may leave files written in an inconsistent state. It may also leave sensitive temporary files on the file system.
...
Tool | Version | Checker | Description | section|
---|---|---|---|---|
Compass/ROSE |
|
| Section | Can detect some violations of this rule. However, it can only detect violations involving |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C++ Secure Coding Standard: ERR06-CPP. Understand the termination behavior of assert() and abort()
ISO/IEC 9899:1999 Section 2011 Section 7.2.1.1, "The assert
macro," and Section 7.20.4.1, "The abort
function"
ISO/IEC PDTR 24772 "REU Termination Strategystrategy"
Bibliography
...