【问题标题】:zlib c++ char size of buffer for compressionzlib c++ char 用于压缩的缓冲区大小
【发布时间】:2017-01-26 21:25:46
【问题描述】:

我正在使用此函数进行 zlib 压缩,并且想知道是否应将 outbuffer 变量设置为特定大小?是否将 char 数组限制为我放在这里的任何内容?我可以在这里输入的长度有限制吗?因为我是用 c++ 编译的,所以将它转换为 std::string 是否有意义?

 /** Compress a STL string using zlib with given compression level and return
     * the binary data. */
    std::string compress_string(const std::string& str, int compressionlevel = 9)
    {
        z_stream zs;                        // z_stream is zlib's control structure
        memset(&zs, 0, sizeof(zs));

        if (deflateInit(&zs, compressionlevel) != Z_OK)
            throw(std::runtime_error("deflateInit failed while compressing."));

        // For the compress
        deflateInit2(&zs, compressionlevel, Z_DEFLATED,MOD_GZIP_ZLIB_WINDOWSIZE + 16,MOD_GZIP_ZLIB_CFACTOR,Z_DEFAULT_STRATEGY) != Z_OK;

        zs.next_in = (Bytef*)str.data();
        zs.avail_in = str.size();           // set the z_stream's input

        int ret;
        char outbuffer[3222768];
        std::string outstring;

        // retrieve the compressed bytes blockwise
        do {
            zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
            zs.avail_out = sizeof(outbuffer);

            ret = deflate(&zs, Z_FINISH);

            if (outstring.size() < zs.total_out) {
                // append the block to the output string
                outstring.append(outbuffer,zs.total_out - outstring.size());
            }
        }
        while (ret == Z_OK);

        deflateEnd(&zs);

        if (ret != Z_STREAM_END) {          // an error occurred that was not EOF
            std::ostringstream oss;
            oss << "Exception during zlib compression: (" << ret << ") " << zs.msg;
            throw(std::runtime_error(oss.str()));
        }

        return outstring;
    }

【问题讨论】:

标签: c++ char zlib


【解决方案1】:

这就是deflateBound() 的用途。在您的deflateInit2() 之后,您可以使用输入大小调用它,它会在压缩不可压缩数据时为您提供可能的扩展范围。

顺便说一句,在同一个结构上调用 deflateInit/deflateInit2 两次会导致大的内存泄漏。只需调用其中一个。

您应该完整阅读zlib documentation。

【讨论】:

  • 您好,您的意思是我应该从我的代码中删除 deflateInit if 语句吗?
  • 您需要删除deflateInit() 或deflateInit2()。第二个永远泄漏第一个分配的内存。顺便说一句,第二个末尾的!= Z_OK 令人困惑,因为它什么也没做。
猜你喜欢
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 2016-08-02
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
相关资源
最近更新 更多