使用 zlib 时,我调用compress()
给出一个Z_BUF_ERROR
当我尝试压缩一个 13G 的文件时,尽管我认为缓冲区分配是正确的。此代码适用于较小的文件。
struct stat infile_stat;
FILE *fp = NULL;
if ((fp = fopen(md_of_name, "r")) == NULL) {
fprintf(stderr,
"Error: Unable to open file %s.\n",
md_of_name);
exit(1);
}
stat(md_of_name, &infile_stat);
size_t u_len = infile_stat.st_size;
char *u_buf = (char *)malloc(u_len);
if (u_buf == NULL) {
fprintf(stderr, "Error: Unable to malloc enough memory for the "
"uncompressed buffer\n");
exit(1);
}
if (fread(u_buf, 1, u_len, fp) < u_len) { // d
fprintf(stderr,
"Error: Unable to read in all of file %s. Exiting.\n ",
md_of_name);
exit(1);
}
fclose(fp);
size_t c_len = compressBound(u_len);
Bytef *c_buf = (Bytef *)malloc(c_len);
if (c_buf == NULL) {
fprintf(stderr, "Error: Unable to malloc enough memory for the "
"compressed BIM buffer\n");
exit(1);
}
fprintf(stderr, "u_len:%lu\tc_len:%lu\tc_buf:%p\n", u_len, c_len, c_buf);
int r = compress(c_buf, &c_len, (Bytef *)u_buf, u_len);
if (r == Z_MEM_ERROR)
fprintf(stderr, "Not enough memory\n");
else if (r == Z_BUF_ERROR)
fprintf(stderr, "Not enough room in the output buffer.\n");
assert(r == Z_OK);
当我在 13922075353 字节的文件上运行此命令时,输出为:
u_len:13922075353 c_len:13926324460 c_buf:0x7f2b82436010
Not enough room in the output buffer.
接下来是断言失败。
UPDATE
我相信这个错误是由于内部铸造问题造成的compress()
zlib 中的函数。如果我是正确的,错误将在第 40 行返回compress.c
在 zlib 1.2.8 中是
if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
That stream.avail_out
变量在上面几行设置为:
stream.avail_in = (uInt)sourceLen;
我认为演员阵容是问题所在。sourceLen
是一个无符号长整型,当它被转换为uInt
位被丢弃。就我而言sourceLen
是13922075353,destLen
是 13926324460(来自compressBound()
),但是因为演员阵容stream.avail_out
是 1041422572。因此出现错误。
如果这是正确的,则缓冲区的大小存在隐式限制。我现在不明白的是为什么缓冲区大小是无符号长的。它们必须是无符号整数。