Search code examples
cfaultatexit

Where should atexit() function go in order to prevent seg fault?


My code works perfectly fine, however when I exit my simpleshell I get a segmentation fault. The final of atexit(final) still gets called and works properly. I think the problem is with the atexit(), because when atexit() is removed from the code I can "exit" (i.e. CNTRL+D) the simpleshell properly. However, restated, once atexit() is inside my code (see below to see where it is), it causes a segmentation fault when I exit (even though "final" executes).

static void final(void) {
    flag = 0;
    assign6 = fopen(".logfile.txt", "a");
    assign62 = fopen(".temp_logger.txt", "r");
      while(fgets(test2, sizeof(test2), assign62))
      {
        fprintf(assign6, test2);
      }
      fclose(assign6);
      fclose(assign62);
      remove(".temp_logger.txt");
    }

Solution

  • You are not checking the assign62 file pointer for proper fopen and it looks like you are deleting it:

    static void final(void) {
        flag = 0;
        assign6 = fopen(".logfile.txt", "a");
        assign62 = fopen(".temp_logger.txt", "r");
        if (assign6 && assign62) {
          while(fgets(test2, sizeof(test2), assign62))
          {
            fprintf(assign6, test2);
          }
          fclose(assign6);
          fclose(assign62);
          remove(".temp_logger.txt");
        }
    }