【发布时间】:2018-07-07 03:02:18
【问题描述】:
以下代码在 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== 大小为 4 的读取无效
==13569== 在 0x4EA7264:fclose@@GLIBC_2.2.5 (iofclose.c:53)
==13569== by 0x400673: main (newmain.cpp:24)
==13569== 地址 0x52042b0 是大小为 552 的块内的 0 个字节已释放
==13569== 在 0x4C2EDEB:免费(在 /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== 块被分配在
==13569== at 0x4C2DB8F: malloc(在 /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); 在 otherfunc() 中释放的内存。但是第 24 行的fclose(fout); 是为了关闭在第 5 行执行的fopen()。
在代码中的任何时间点,每当调用fclose() 时,总会有一个打开的fopen()。为什么这是 valgrind 报告的无效读取?
【问题讨论】: