【发布时间】:2012-09-18 19:24:41
【问题描述】:
我一直在使用 libzip 来处理 zip 文件,并且我的代码基于 rodrigo 对this question 的回答中的示例。这是他的代码,供快速参考:
#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”时抱怨未初始化的值。
==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; 标记在末尾将消除它。
(我会在原始答案上留下评论以引起对该问题的关注,但我没有必要的代表。)
【问题讨论】:
-
堆栈跟踪有点奇怪,你调用 zip_fopen 但它说你在 zip_fopen_index 中。看不到有任何
#define定义了另一个,所以必须询问它是否是正确的堆栈跟踪。 -
我同意!我在 zip.h 中看不到类似的东西,这是在这里询问的另一个原因。绝对是正确的跟踪,我只是再次运行它来检查。我很想看看是否有其他人可以复制这个。
-
您必须查看
inflateReset2()的源代码,以确定在初始化之前将哪个变量用作条件。我敢肯定,源代码也包含zip_fopen_index()问题的答案。 -
在下面的答案中添加了更多信息,警告似乎特定于 Ubuntu 正在使用的 zlib 版本。