exit(), abort() and assert()


void exit ( int status ); 

exit() terminates the process normally.
status: Status value returned to the parent process. Generally, a status value of 0 or EXIT_SUCCESS indicates success, and any other value or the constant EXIT_FAILURE is used to indicate an error. exit() performs following operations.
* Flushes unwritten buffered data.
* Closes all open files.
* Removes temporary files.
* Returns an integer exit status to the operating system.

The C standard atexit() function can be used to customize exit() to perform additional actions at program termination.

Example use of exit.

/* exit example */
#include <stdio.h>
#include <stdlib.h>
int main ()
  FILE * pFile;
  pFile = fopen ("myfile.txt", "r");
  if (pFile == NULL)
    printf ("Error opening file");
    exit (1);
    /* file operations here */
  return 0;


 void abort ( void );

Unlike exit() function, abort() may not close files that are open. It may also not delete temporary files and may not flush stream buffer. Also, it does not call functions registered with atexit().

This function actually terminates the process by raising a SIGABRT signal, and your program can include a handler to intercept this signal (see this).

So programs like below might not write “Geeks for Geeks” to “tempfile.txt”

int main()
  FILE *fp = fopen("C:\\myfile.txt", "w");
  if(fp == NULL)
    printf("\n could not open file ");
  fprintf(fp, "%s", "Geeks for Geeks");
  /* ....... */
  /* ....... */
  /* Something went wrong so terminate here */  
  return 0;  

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.


void assert( int expression );

If expression evaluates to 0 (false), then the expression, sourcecode filename, and line number are sent to the standard error, and then abort() function is called. If the identifier NDEBUG (“no debug”) is defined with #define NDEBUG then the macro assert does nothing.

Common error outputting is in the form:

Assertion failed: expression, file filename, line line-number


void open_record(char *record_name)
    assert(record_name != NULL);
    /* Rest of code */

int main(void)

Related Article :
exit() vs _Exit() in C and C++

This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect in the above article or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up

Practice Tags :
Article Tags :
Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:

3.1 Average Difficulty : 3.1/5.0
Based on 34 vote(s)

User Actions