The C Standard, Section subclause 7.2.1.1 [ISO/IEC 9899:2011], defines assert()
to have the following behavior:
...
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 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 see ERR00-C. Adopt and implement a consistent and comprehensive error-handling policy).)
See ERR04-C. Choose an appropriate termination strategy for more information on program termination strategies and MSC11-C. Incorporate diagnostic tests using assertions for more information on using the assert()
macro.
...
This noncompliant code example defines a function that is called before the program exits to clean up.:
Code Block | ||||
---|---|---|---|---|
| ||||
void cleanup(void) { /* Delete temporary files, restore consistent state, etc. */ } int main(void) { if (atexit(cleanup) != 0) { /* Handle error */ } /* ... */ assert(/* somethingSomething bad didn't happen */); /* ... */ } |
...
In this compliant solution, the call to assert()
is replaced with an if
statement that calls exit()
to ensure that the proper termination routines are run.:
Code Block | ||||
---|---|---|---|---|
| ||||
void cleanup(void) { /* Delete temporary files, restore consistent state, etc. */ } int main(void) { if (atexit(cleanup) != 0) { /* Handle error */ } /* ... */ if (/* somethingSomething bad happened */) { exit(EXIT_FAILURE); } /* ... */ } |
...
Unsafe use of abort()
may leave files written in an inconsistent state. It may also leave sensitive temporary files on the file system.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
ERR06-C |
Medium |
Unlikely |
Medium | P4 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Astrée |
| bad-function bad-macro-use | Supported | ||||||
Compass/ROSE |
Can detect some violations of this rule. However, it can only detect violations involving | |||||||||
LDRA tool suite |
| 44 S | Enhanced enforcement | ||||||
Parasoft C/C++test |
| CERT_C-ERR06-a |
Do not use assertions | |||||||||
PC-lint Plus |
| 586 | Fully supported | ||||||
PVS-Studio |
| ||||||||
RuleChecker |
| bad-function bad-macro-use | Supported |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
SEI CERT C++ |
Coding Standard | VOID ERR06-CPP. Understand the termination behavior of assert() and abort() |
ISO/IEC TR 24772:2013 | Termination Strategy [REU] |
Bibliography
...