...
Because assert()
calls abort()
, cleanup functions registered with atexit()
are not called. If the intention of the programmer is properly cleanup in the case of a failed assertion, a signal handler that calls exit()
should be installed to handle SIGABRT
then runtime assertions should be replaced with static assertions where possible (see DCL03-A. 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 ERR00-A. Adopt and implement a consistent and comprehensive error handling policy).
See ERR04-A. Choose an appropriate termination strategy for more information on program termination strategies and MSC11-A. Incorporate diagnostic tests using assertions for more information on using the assert()
macro.
Non-Compliant Code Example
Code Block | ||
---|---|---|
| ||
void cleanup(void) { /* delete temporary files, restore consistent state, etc. */ } int main(void) { atexit(cleanup); /* ... */ assert(/* something bad didn't happen */); /* ... */ } |
If the assert()
fails, the cleanup()
function is not called.
Compliant Solution
In this compliant solution, the call to assert()
is replaced with an if statement which calls exit()
to ensure that the proper termination routines are run.
Code Block | ||
---|---|---|
| ||
void sigabrt_handler(int signum) { exit(EXIT_FAILURE); } void cleanup(void) { /* delete temporary files, restore consistent state, etc */ } int main(void) { atexit(cleanup); signal(SIGABRT, sigabrt_handler); /* ... */ if assert(/* something bad didn't happenhappened */) { exit(EXIT_FAILURE); } /* ... */ } |
...
Risk Analysis
Unsafe usage of abort()
may leave files written in an inconsistent state. It may also leave sensitive temporary files on the filesystem.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
ERR06-A | medium | unlikely | medium | P4 | 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 7.2.1.1, "The {{assert}} macro", 7.20.4.1, "The {{abort}} function" |
...