Zlib deflate和动态输出缓冲区

zlib deflate and dynamic output buffer

本文关键字:输出 缓冲区 动态 deflate Zlib      更新时间:2023-10-16

好吧,我重做了我的问题一点,我不明白如何正确地压缩内容到动态缓冲区,谁需要不断重新分配。我稍微重写了一下我的代码,它只在没有重新分配缓冲区的情况下工作,所以在少量数据上,重新分配以某种方式中断了输出流。

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("badrn"); exit(0); }

        total_buf_size =deflateBound(&gzip_stream,strlen(str));
        printf("d_bound_init=%drn",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=%drn",gzip_stream.avail_out);
        t_size = deflateBound(&gzip_stream,strlen(str));
        printf("d_bound=%drn",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_stream的指针,是否仍然指向数据的开始?所以基本上,如果我使用多个重新分配,最终数据被打破。结束:我如何正确检测,我需要为我的输出deflate缓冲区分配多少数据,以及在z_stream中使用动态重新分配缓冲区是否正确?

realloc确保在新大小不适合旧内存位置时将数据复制到新位置。calloc只是将分配的内存归零,并且不复制旧数据。因此,必须将较大的值传递给calloc。当你传递这么大的数字时,你可能只需要调用calloc一次,而realloc可以接受更小的增量。有意义吗?

欢呼