How to use the abort function to cause abnormal program termination (without cleaning up) in C

3 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>

// In C, abort() causes the program to terminate abnormally immediately. Unlike exit(), 
// it does not perform normal cleanup such as calling functions registered with atexit() 
// or flushing all open streams.

int main () {
    FILE *fp;
   
    fp = fopen("afile.txt","r" );
    if (fp == NULL) {
        fprintf(stderr, "error opening afile.txt abort()\n");
        abort();
    }
    printf("Close afile.txt\n");
    fclose(fp);
   
    return(0);
}



/*
run:

error opening afile.txt abort()
Command terminated by signal 6

*/

 



answered Dec 22, 2021 by avibootz
edited Oct 9 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

// In C, abort() causes the program to terminate abnormally immediately. Unlike exit(), 
// it does not perform normal cleanup such as calling functions registered with atexit() 
// or flushing all open streams.

int main(void) {
    printf("Program will abort\n");

    abort();

    printf("This line is never executed\n");
    
    return 0;
}


/*
run:

Program will abort
Aborted

*/

 



answered Oct 9 by avibootz
0 votes
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>

// In C, abort() causes the program to terminate abnormally immediately. Unlike exit(), 
// it does not perform normal cleanup such as calling functions registered with atexit() 
// or flushing all open streams.

int main(void) {
    int *p = NULL;

    if (p == NULL) {
        abort();  // Fatal error
    }

    // equivalently, using assert:
    // assert(p != NULL);
    // Failed assertion typically calls abort() internally.
}


/*
run:

Aborted

*/

 



answered Oct 9 by avibootz
...