Try*_*yer 0 c++ linux fopen valgrind
以下代码在 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;
}
Run Code Online (Sandbox Code Playgroud)
当运行 valgrind 时,valgrind 给出以下警告:
==13569== 大小 4 读取无效
==13569== 在 0x4EA7264:fclose@@GLIBC_2.2.5 (iofclose.c:53)
==13569== 由 0x400673: main (newmain.cpp:24)
==13569== 地址 0x52042b0 是大小为 552 的块内的 0 字节已释放
==13569== 在 0x4C2EDEB:免费(在 /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so 中)
==13569== 由 0x4EA7362: fclose@@GLIBC_2.2.5 (iofclose.c:84)
==13569== 由 0x4005CD: otherfunc(_IO_FILE*) (newmain.cpp:4)
==13569== 由 0x400667: main (newmain.cpp:22)
==13569== 块被分配在
==13569== 在 0x4C2DB8F:malloc(在 /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so 中)
==13569== 由 0x4EA7CDC: __fopen_internal (iofopen.c:69)
==13569== 由 0x400657: main (newmain.cpp:19)
本质上,它被抱怨fclose(fout);上线24被关闭该被释放在第4行的已释放的存储器fclose(fout);内otherfunc()。但是第 24 行的fclose(fout);目的是结束第fopen()5 行的执行。
在代码中的任何时间点,无论何时 afclose()被调用,总是只有一个 open fopen()。为什么这是 valgrind 报告的无效读取?
otherfunc按值获取文件指针。所以你在第 5 行分配的值在从otherfunc那里返回后丢失了,当它返回到那里时,它main的值fout保持不变。它包含您在第 4 行关闭的悬空文件指针值。因此,close对第 24 行的调用将收到无效指针。