繁体   English   中英

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 ==读取的4号无效

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

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

== 13569 ==地址0x52042b0是大小为552的块内的0个字节

== 13569 == at 0x4C2EDEB:free(在/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); 旨在关闭第5行执行的fopen()

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM