C++ zlib deflate和动态输出缓冲
好的,我重新提出了我的问题,我不知道如何将内容适当地压缩到动态缓冲区中,动态缓冲区需要不断地重新分配。我重新编写了一点代码,只有在缓冲区没有重新分配的情况下它才会工作,所以对于少量数据,重新分配会以某种方式中断输出流C++ zlib deflate和动态输出缓冲,c++,c,gzip,zlib,deflate,C++,C,Gzip,Zlib,Deflate,好的,我重新提出了我的问题,我不知道如何将内容适当地压缩到动态缓冲区中,动态缓冲区需要不断地重新分配。我重新编写了一点代码,只有在缓冲区没有重新分配的情况下它才会工作,所以对于少量数据,重新分配会以某种方式中断输出流 void test_deflate_dynamic(char*str) { if(store == NULL) // first call to the function allocate some memory etc { gzip_strea
void test_deflate_dynamic(char*str)
{
if(store == NULL) // first call to the function allocate some memory etc
{
gzip_stream.zalloc = Z_NULL;
gzip_stream.zfree = Z_NULL;
gzip_stream.opaque = Z_NULL;
result = deflateInit(&gzip_stream,9);
if(result!=Z_OK) { printf("bad\r\n"); exit(0); }
total_buf_size =deflateBound(&gzip_stream,strlen(str));
printf("d_bound_init=%d\r\n",total_buf_size);
store = realloc(store,total_buf_size); // first allocation
gzip_stream.avail_out = total_buf_size;
gzip_stream.next_out = store;
gzip_stream.avail_in = strlen(str)+1;
gzip_stream.next_in = str;
result = deflate(&gzip_stream,Z_NO_FLUSH);
}
else
{
gzip_stream.avail_in = strlen(str)+1;
gzip_stream.next_in = str;
int t_size;
printf ("avail_out=%d\r\n",gzip_stream.avail_out);
t_size = deflateBound(&gzip_stream,strlen(str));
printf("d_bound=%d\r\n",t_size);
total_buf_size += t_size;
gzip_stream.avail_out = total_buf_size;
store = realloc(store,total_buf_size);
gzip_stream.next_out = store;
result = deflate(&gzip_stream,Z_NO_FLUSH);
}
}
如您所见,我正在使用函数
deflateBound
来检测需要分配多少数据,因此首先,使用deflateBound是否正确?其次,被realloc
修改后重新分配给z_流的指针是否仍然指向数据的开头?因此,基本上,如果我使用多个重新分配,最终数据将被破坏。结束:如何正确检测,需要为输出deflate缓冲区分配多少数据,以及在z_流中使用动态重新分配缓冲区是否正确?realloc
确保在新大小不适合旧内存位置时将数据复制到新位置calloc
只将分配的内存归零,不复制旧数据。因此,必须将较大的值传递给calloc
。当您传递如此大的数字时,您可能只需要调用一次calloc
,而realloc
可以接受较小的增量。有道理吗
干杯所以我假设我不能将realloc与z_stream一起使用,因为缓冲区应该只设置一次,所以deflate将从这个缓冲区中生成正确的压缩内容,我不能realloc它,对吗?应该预先分配吗?请再看我的问题,我做了很多编辑。你做得对还是错还取决于你如何调用test\u deflate\u dynamic()
,以及你如何处理它生成的数据。因此,你必须发布一个完整的程序。