即使在NULL检查后使用freopen,fclose(stdout)也会导致崩溃

Mar*_*olo 0 c fclose freopen

我试图使用freopen打印stdout到文件,下面的代码崩溃.我是NULL检查,我很确定我在程序中的其他地方没有分段错误,因为我验证了我的所有malloc都是正确的.

程序到达时会崩溃fclose(stdout),并且不会打印我附加的错误信息来检查它.该printf("\nTestBeforeClose");行打印但printf("\nTestAfterClose");不打印.

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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的var结构:

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

var * head = NULL;
Run Code Online (Sandbox Code Playgroud)

Rob*_*b K 5

当然printf("\nTestAfterClose\n");不打印.您刚刚关闭的printf打印件stdout.