关于c ++:使用Valgrind检查时,Libzip示例包含未初始化的值

Libzip example contains uninitialised values when checked with Valgrind

我一直在使用libzip处理zip文件,并且将我的代码基于在rodrigo对此问题的答案中找到的示例。 这是他的代码,以供快速参考:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <zip.h>

int main()
{
    //Open the ZIP archive
    int err = 0;
    zip *z = zip_open("foo.zip", 0, &err);

    //Search for the file of given name
    const char *name ="file.txt";
    struct zip_stat st;
    zip_stat_init(&st);
    zip_stat(z, name, 0, &st);

    //Alloc memory for its uncompressed contents
    char *contents = new char[st.size];

    //Read the compressed file
    zip_file *f = zip_fopen(z,"file.txt", 0);
    zip_fread(f, contents, st.size);
    zip_fclose(f);

    //And close the archive
    zip_close(z);
}

我将后来从Valgrind获得的错误追溯到此代码-使用'zip_fopen()`打开压缩后的" file.txt"时,它抱怨未初始化的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
==29256== Conditional jump or move depends on uninitialised value(s)
==29256==    at 0x5B4B290: inflateReset2 (in /usr/lib/libz.so.1.2.3.4)
==29256==    by 0x5B4B37F: inflateInit2_ (in /usr/lib/libz.so.1.2.3.4)
==29256==    by 0x4E2EB8C: zip_fopen_index (in /usr/lib/libzip.so.1.0.0)
==29256==    by 0x400C32: main (main.cpp:24)
==29256==  Uninitialised value was created by a heap allocation
==29256==    at 0x4C244E8: malloc (vg_replace_malloc.c:236)
==29256==    by 0x5B4B35B: inflateInit2_ (in /usr/lib/libz.so.1.2.3.4)
==29256==    by 0x4E2EB8C: zip_fopen_index (in /usr/lib/libzip.so.1.0.0)
==29256==    by 0x400C32: main (main.cpp:24)
==29256==
==29256==
==29256== HEAP SUMMARY:
==29256==     in use at exit: 71 bytes in 1 blocks
==29256==   total heap usage: 26 allocs, 25 frees, 85,851 bytes allocated
==29256==
==29256== 71 bytes in 1 blocks are definitely lost in loss record 1 of 1
==29256==    at 0x4C24A72: operator new[](unsigned long) (vg_replace_malloc.c:305)
==29256==    by 0x400BEE: main (main.cpp:19)

我看不到这段代码中的未初始化值来自哪里。 任何人都可以追查此事,还是问题在于libzip本身? 我应该切换到另一个zip库,例如Minizip吗?

编辑:71字节是file.txt的内容,该内容在末尾用delete[] contents;标记读取将消除这种情况。

(我会在原始答案上留下评论,以引起对此问题的注意,但我没有必要的代表。)


你让我看起来:)

是的,这是zlib(由libzip使用)内部的错误,因为在同一调用上分配和使用内存都在inflateInit2_内部。 您的代码甚至没有机会进入该内存。

我可以使用zlib 1.2.3重复该问题,但在1.2.7中不再显示。 我没有适用于1.2.3的代码,但是如果您正在看的话,我会检查state的初始化以及在inflateReset2中如何使用它。

编辑:跟踪问题,我为zlib(1.2.3.4)下载了Ubuntu的源程序包,令人讨厌的是:

1
if (state->wbits != windowBits && state->window != Z_NULL) {

wbits在此之前未初始化,并且将引起警告。 奇怪的是,原始的zlib 1.2.3或1.2.4都没有这个问题,对于Ubuntu来说似乎是唯一的。 1.2.3甚至没有功能inflateReset2,而1.2.4拥有它;

1
if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {

由于window先前已初始化为Z_NULL,因此不会发生未初始化的wbits读取。