【问题标题】:Valgrind invalid read on FILE*Valgrind 无效读取 FILE*
【发布时间】: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 报告的无效读取?

【问题讨论】:

    标签: c++ linux valgrind fopen


    【解决方案1】:

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

    【讨论】:

    • 有没有办法用 FILE* 绕过这个问题?我需要将相同的文件指针(指向相同的“text.txt”文件)从 main 传递给多个函数。视情况而定,可能需要在不同的功能中关闭、删除和重新创建文件。
    • @Tryer 只是通过引用传递文件指针。或者传递一个指向文件指针的指针(因为这似乎实际上是一个关于 C 的问题)。
    • @user4581301 和 VTT。是的,上面的 FILE *& 会导致 valgrind 没有抱怨的代码。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-04-09
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多