Valgrind 对 FILE 的读取无效*

Valgrind invalid read on FILE*

以下代码在 ubuntu 上构建时会创建一个可执行文件。

#include <stdio.h>

void otherfunc(FILE* fout){
    fclose(fout);//Line 4
    fout = fopen("test.txt", "w");//Delete contents and create a new file//Line 5
    setbuf(fout, 0);//Line 6
}

int main() {
    FILE *fout = fopen("test.txt", "r");//Line 10
    if (fout) {
        //file exists and can be opened
        fclose(fout);//Line 13
        fout = fopen("test.txt", "a");//Line 14
        setbuf(fout, 0);
    }
    else {
        //file doesn't exists or cannot be opened 
        fout = fopen("test.txt", "a");//Line 19
    }
    
    otherfunc(fout);//Line 22
    
    fclose(fout);//Line 24
    return 0;
}

当运行通过valgrind时,valgrind给出以下警告:

==13569== Invalid read of size 4

==13569== at 0x4EA7264: fclose@@GLIBC_2.2.5 (iofclose.c:53)

==13569== by 0x400673: main (newmain.cpp:24)

==13569== Address 0x52042b0 is 0 bytes inside a block of size 552 free'd

==13569== at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)

==13569== by 0x4EA7362: fclose@@GLIBC_2.2.5 (iofclose.c:84)

==13569== by 0x4005CD: otherfunc(_IO_FILE*) (newmain.cpp:4)

==13569== by 0x400667: main (newmain.cpp:22)

==13569== Block was alloc'd at

==13569== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)

==13569== by 0x4EA7CDC: __fopen_internal (iofopen.c:69)

==13569== by 0x400657: main (newmain.cpp:19)

本质上,它是在抱怨第 24 行的 fclose(fout); 正在关闭一个已经释放的内存,该内存在 otherfunc() 中的第 4 fclose(fout); 行释放。但是第 24 行的 fclose(fout); 是为了关闭第 5 行上执行的 fopen()

在代码中的任何时间点,每当调用 fclose() 时,总是只有一个打开 fopen()。为什么这是 valgrind 报告的无效读取?

otherfunc 按值获取文件指针。因此,您在第 5 行分配的值在从 otherfunc 返回后丢失,并且当它 returns 进入 mainfout 的值保持不变。它包含您已在第 4 行关闭的悬空文件指针值。因此,在第 24 行调用 close 将收到无效指针。