以下代码在 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);
正在关闭一个已经释放的内存,该内存在第 4 行 fclose(fout);
中被释放其他函数()
。但是第 24 行的 fclose(fout);
是为了关闭第 5 行执行的 fopen()
。
在代码中的任何时间点,每当 fclose()
被调用时,总是恰好有一个打开的 fopen()
。为什么这是 valgrind 报告的无效读取?
最佳答案
otherfunc
按值获取文件指针。因此,您在第 5 行分配的值在从 otherfunc
返回后丢失,当它返回到 main
时,fout
的值保持不变.它包含您已在第 4 行关闭的悬空文件指针值。因此,在第 24 行调用 close
将收到无效指针。
关于c++ - Valgrind 对 FILE 的读取无效*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48483947/