cfclosefreopen

fclose(stdout) causes a crash when using freopen even after NULL check


I am trying to print stdout to file using freopen and the code below crashes. I am NULL checking and I'm fairly sure I don't have a segmentation fault somewhere else in the program since I verified that all my mallocs are correct.

The program crashes when it reaches the fclose(stdout) and doesn't print the error messgage I attached to check it. The printf("\nTestBeforeClose"); line prints but the printf("\nTestAfterClose"); does not.

int printAllVarRedir(char * filename, int redirmarker) {
    var *current = NULL;

    if (redirmarker == 1) {
        if (freopen(filename, "w", stdout) == NULL) {
            perror("Unable to open file");
            return 1;
        } else {
            if (head == NULL) {
                perror("No Variables");
                fclose(stdout);
                return 1;
            } else {
                current = head;
                printf("%s=%s. Address is %p.Next is:%p\n", current->varname, current->value, current, current->next);
                while (current->next != NULL) {
                    current = current->next;
                    printf("%s=%s. Address is %p.Next is:%p\n", current->varname, current->value, current,
                           current->next);
                }
                printf("\nTestBeforeClose");
                if (fclose(stdout) == EOF) {
                    printf("\nError is %s\n", strerror(errno));
                }
                printf("\nTestAfterClose\n");
                return 0;
            }
        }
    }
}

This is the var struct I am using:

typedef struct varlist{
    char * varname;
    char * value;
    struct varlist * next;
}var;

var * head = NULL;

Solution

  • Of course printf("\nTestAfterClose\n"); doesn't print. printf prints to stdout which you've just closed.