...
The quickest way to terminate a program, abort()
takes no parameter, and always signifies abnormal termination to the operating
system.
Code Block | ||
---|---|---|
| ||
#include <stdlib.h> /* ... */ if (/* something really bad happened */) { abort(); } |
The abort() function causes abnormal program termination to occur,
unless the signal SIGABRT is being caught and the signal handler does
not return.
Whether open streams with unwritten buffered data are flushed, open
streams are closed, or temporary files are removed is
implementation-defined.
Summary
Function | Closes file descriptors | Flushes buffers | Deletees | Calls |
---|---|---|---|---|
abort() | unspecified | unspecified | unspecified | no |
_Exit(status) | yes | unspecified | unspecified | no |
exit(status) | yes | yes | yes | yes |
...
You can use the Standard C atexit() function to customize exit() to
perform additional actions at program termination.
...
"registers" the turn_gizmo_off()
function so that a subsequent
call to exit()
will invoke turn_gizmo_off();
as it terminates
the program. The C standard says that atexit()
should let you
register up to 32 functions.
atexit()
is only called by exit()
or upon normal completion of
main()
. It is not called by _Exit()
or abort()
.
...
In this example, abort()
is called after data is sent to an open
file descriptor. The data may or may not actually get written to the
file.
Code Block | ||
---|---|---|
| ||
#include <stdlib.h> #include <stdio.h> int write_data() { const char* filename = "hello.txt"; FILE *f = fopen(filename, "w"); if (f == NULL) { /* handle error */ } fprintf(f, "Hello, World\n"); /* ... */ abort(); /* oops! data might not get written! */ /* ... */ return 0; } int main() { write_data(); return 0; } |
...
In this solution, the call to abort()
is replaced with exit()
,
which guarantees that buffered I/O data is flushed to the file
descriptor and the file descriptor is properly closed.
...
While this particular example benefits from calling exit()
over
abort()
, there will be situations where abort()
is the better
choice. Usually this will occur if one does not want to close any file
descriptors or call any handlers registered with atexit()
, for
instance, if the speed of terminating the program is critical.
...
An usage of abort()
or _Exit()
in place of exit()
may
leave files written in an inconsistent state. It may also leave
sensitive temporary files on the filesystem.
...
Search for vulnerabilities resulting from the violation of this rule
on the CERT website.
References
...
*[|ERR03-A. Use
runtime-constraint handlers when calling functions defined by
TR24731-1]* *[!CERT C Secure
Coding Standard^button_arrow_up.png!|13. Error Handling
(ERR)]* *[!CERT C Secure Coding
Standard^button_arrow_right.png!|ERR03-A. Use runtime-constraint
handlers when calling functions defined by TR24731-1]*