C exit(), abort() and assert() Functions
Last Updated :
21 Sep, 2023
The C exit(), abort(), and assert() functions are all used to terminate a C program but each of them works differently from the other. In this article, we will learn about exit, abort, and assert functions and their use in C programming language.
1. exit() in C
The C exit() function is a standard library function used to terminate the calling process. When exit() is called, any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal.
It is defined inside the <stdlib.h> header file.
Syntax of exit() in C
void exit(int status);
Parameters
The exit() function in C only takes a single parameter status which is the exit code that is returned to the caller i.e. either the operating system or parent process. There are two valid values we can use as the status each having a different meaning. They are as follows:
- 0 or EXIT_SUCCESS: 0 or EXIT_SUCCESS means that the program has been successfully executed without encountering any error.
- 1 or EXIT_FAILURE: 1 or EXIT_FAILURE means that the program has encountered an error and could be executed successfully.
Note: We can actually return any non-zero return value in case of failure.
Return Value
- This function doesn't return any value to the current process so its return type is void. Instead, it returns the status value to the parent process which is returned through a method different than the return value.
Example 1: C Program to Illustrate the exit() Function
C
// C Program to demonstrate the syntax of exit() function
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* pFile;
pFile = fopen("myfile.txt", "r");
if (pFile == NULL) {
printf("Error opening file");
// terminating the process if the file is not opened
exit(1);
}
else {
/* file operations here */
}
return 0;
}
How exit() in C works?
When called, the exit() function in C performs the following operations:
- Flushes unwritten buffered data.
- Closes all open files.
- Removes temporary files.
- Returns an integer exit status to the operating system.
Example 2: Passing an integer value greater than 255 to the exit() function in C
C
// C Program to verify the status value
// size of the exit() function
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
if (pid == 0) {
// passing value more than 255
exit(9999);
}
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
printf("Exit code: %d\n", exit_status);
}
return 0;
}
Explanation
In the above function, instead of 9999, the status value is 15. It is an effect of 8-bit integer overflow. After 255 (all 8 bits set) comes 0. As the exit() supports only 8-bit integer values, the output is "exit code modulo 256". The output above is actually the modulo of the value 9999 and 256 i.e. 15.
The C standard atexit() function can be used to customize exit() to perform additional actions at program termination.
2. abort() in C
The C abort() function is the standard library function that can be used to exit the C program. But unlike the exit() function, abort() may not close files that are open. It may also not delete temporary files and may not flush the stream buffer. Also, it does not call functions registered with atexit().
Syntax of abort() in C
void abort(void);
Parameters
- The C abort() function does not take any parameter and does not have any return value. This function actually terminates the process by raising a SIGABRT signal, and your program can include a handler to intercept this signal.
Return Value
- The abort() function in C does not return any value.
Example: C Program to Illustrate the abort() Function
C
// C program to demonstrate the syntax of abort function
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* fp = fopen("C:\\myfile.txt", "w");
if (fp == NULL) {
printf("\n could not open file ");
getchar();
exit(1);
}
fprintf(fp, "%s", "Geeks for Geeks");
/* ....... */
/* ....... */
/* Something went wrong so terminate here */
abort();
getchar();
return 0;
}
Output
timeout: the monitored command dumped core
/bin/bash: line 1: 35 Aborted
Note: If we want to make sure that data is written to files and/or buffers are flushed then we should either use exit() or include a signal handler for SIGABRT.
3. assert() in C
The C assert() function is a macro defined inside the <assert.h> header file. It is a function-like macro that is used for debugging. It takes an expression as a parameter,
- If the expression evaluates to 1 (true), the program continue to execute.
- If the expression evaluates to 0 (false), then the expression, source code filename, and line number are sent to the standard error, and then the abort() function is called.
Syntax of assert() in C
void assert(expression);
Parameters
- expression: It is the condition we want to evaluate.
Return Value
- The assert() function does not return any value.
If the identifier NDEBUG ("no debug") is defined with #define NDEBUG then the macro assert does nothing. Common error output is in the form: Assertion failed: expression, file filename, line line-number.
Example: C Program to Illustrate the assert() Function
C
// C Program to demonstrate the use of assert() function
#include <assert.h>
#include <stdio.h>
void open_record(char* record_name)
{
assert(record_name != NULL);
/* Rest of code */
}
int main(void) { open_record(NULL); }
Output
test.c:7: open_record: Assertion `record_name != ((void *)0)' failed.
timeout: the monitored command dumped core
/bin/bash: line 1: 34 Aborted
Similar Reads
Functions that are executed before and after main() in C
With GCC family of C compilers, we can mark some functions to execute before and after main(). So some startup code can be executed before main() starts, and some cleanup code can be executed after main() ends. For example, in the following program, myStartupFun() is called before main() and myClean
1 min read
atexit() function in C/C++
The function pointed by atexit() is automatically called without arguments when the program terminates normally. In case more than one function has been specified by different calls to the atexit() function, all are executed in the order of a stack (i.e. the last function specified is the first to b
3 min read
C Function Arguments and Function Return Values
Prerequisite: Functions in C A function in C can be called either with arguments or without arguments. These functions may or may not return values to the calling functions. All C functions can be called either with arguments or without arguments in a C program. Also, they may or may not return any
6 min read
exit() vs _Exit() in C/C++
exit() and _Exit() in C/C++ are very similar in functionality. However, there is one difference between exit() and _Exit() and it is that exit() function performs some cleaning before the termination of the program like connection termination, buffer flushes, etc. exit() In C, exit() terminates the
3 min read
fegetexceptflag() function in C/C++
The fegetexceptflag() function in C/C++ is specified in header file fenv.h and gets floating point exception flags. This function store the raised exception in the point specified by flagp . Syntax: int fegetexceptflag(fexcept_t* flagp, int excepts) Parameters: The function accepts two mandatory par
2 min read
fegetenv() function in C/C++
The fegetenv() function in C/C++ is specified in header file cfenv.h and attempts to store the current state of the floating-point environment in the object pointed by envp. The floating point environment is a set of status flags and control modes which includes both floating point exception and the
4 min read
C fopen() Function
In C, the fopen() function is used to open a file in the specified mode. The function returns a file pointer (FILE *) which is used to perform further operations on the file, such as reading from or writing to it. If the file exists then the fopen() function opens the particular file else a new file
5 min read
Assertions in C/C++
Assertions are statements used to test assumptions made by programmers, such as validating logic or invariants in the code. For example, we may use an assertion to check if the index of an array is within valid bounds during development. Following is the syntax for assertion. void assert( int expres
2 min read
Undefined Behavior in C and C++
When we run a code, sometimes we see absurd results instead of expected output. So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programm
7 min read
feupdateenv() function in C++
The feupdateenv() function in C++ first saves currently raised floating-point exceptions. It restores the floating-point environment from the given fenv_t object and then raises the exceptions which were saved previously.Syntax: int feupdateenv( fenv_t* envp ) Parameters: It accepts a single mandato
2 min read