- The C Standard Library
- C Library - Home
- C Library - <assert.h>
- C Library - <complex.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <fenv.h>
- C Library - <float.h>
- C Library - <inttypes.h>
- C Library - <iso646.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdalign.h>
- C Library - <stdarg.h>
- C Library - <stdbool.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <tgmath.h>
- C Library - <time.h>
- C Library - <wctype.h>
- C Standard Library Resources
- C Library - Quick Guide
- C Library - Useful Resources
- C Library - Discussion
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
C library - abort() function
The C stdlib library abort() function allows us to terminate or exit from the program by raising the 'SIGABRT' signal.
The 'SIGABRT' signal is one of the signals used in operating systems to indicate an abnormal termination of a program.
This function is useful to find the critical error, debugging, or fallback safety.
Syntax
Following is the C library syntax of the abort() function −
void abort(void)
Parameters
This function does not accepts any parameters.
Return Value
This function does not returns any values.
Example 1
In this example, we create a basic c program to demonstrate the use of abort() function.
#include <stdio.h> #include <stdlib.h> int main(void) { FILE *stream; if ((stream = fopen("D:tpwork/tutorialspoint", "r")) == NULL) { perror("Could not open data file"); abort(); } return 0; }
Output
Following is the output −
Could not open data file: No such file or directory
Example 2
Let's create another, we use the abort() function when the allocated memory is 'NULL'. Otherwise prints value of the ptr.
#include <stdio.h> #include <stdlib.h> int main() { int *ptr; ptr = (int*)malloc(sizeof(int)); if (ptr == NULL) { printf("Memory allocation failed. Aborting program.\n"); abort(); } // If allocation was successful, use the allocated memory *ptr = 5; printf("Value at ptr: %d\n", *ptr); // Free the allocated memory free(ptr); return 0; }
Output
Following is the output −
Value at ptr: 5
Example 3
Here, we create a C program that opens a file. If the file is not available, we immediately abort the program.
#include <stdio.h> #include <stdlib.h> int main () { printf("Opening the tutorialspoint.txt\n"); FILE *fp; // open the file fp = fopen("tutorialspoint.txt", "r"); if (fp == NULL) { perror("Aborting the program"); abort(); } else { printf("File opened successfully\n"); } printf("Close tutorialspoint.txt\n"); // close the file fclose(fp); return(0); }
Output
Following is the output −
Opening the tutorialspoint.txt Aborting the program: No such file or directory Aborted (core dumped)