How to use the exit function to cause normal program termination with cleanup in C

3 Answers

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

int main() {
    printf("exit()\n");

    exit(EXIT_SUCCESS); // exit(0);
    
    printf("code that will never run");
}


 
 
 
/*
run
 
exit()
 
*/

 



answered May 1, 2021 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

void cleanup(void) {
    printf("Performing cleanup...\n");
}

int main(void)
{
    atexit(cleanup);

    printf("Program is running\n");

    exit(EXIT_SUCCESS);

    return 0;  // Never reached
}


/*
run:

Program is running
Performing cleanup...

*/

 



answered Oct 10 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

char *buffer;

void cleanup(void)
{
    free(buffer);
    printf("Memory released\n");
}

int main(void)
{
    buffer = malloc(100);
    if (buffer == NULL)
        exit(EXIT_FAILURE);

    atexit(cleanup);

    /* Program logic */

    exit(EXIT_SUCCESS);
}



/*
run:

Memory released

*/

 



answered Oct 10 by avibootz
...