zlib内存不足的问题

Out of memory problem with zlib

本文关键字:问题 内存不足 zlib      更新时间:2023-10-16

我想使用zlib压缩字符串。如果我在大约一个小时后将这个函数放入循环中,"compress"返回-4,这意味着Z_MEM_ERROR。有人知道问题出在哪里吗?

std::string compressData(std::string const& line)
{
    char *src=(char*)line.c_str();
    int srcLen=strlen(src);
    int destLen=compressBound(srcLen);
    char *dest=new char[destLen];
    int result=compress((unsigned char *)dest ,(uLongf*)&destLen ,(const unsigned char *)src ,srcLen );
    QByteArray sd = QByteArray::fromRawData(dest, destLen);
    QString hexZipData (sd.toHex());
    std::string hexZipDataStr = hexZipData.toStdString();
    if( result != Z_OK)
    {
       hexZipDataStr = "";
       std::cout << "error !"; 
    }
    delete []dest;
    dest = NULL;
    return hexZipDataStr;
}

我能看到的唯一可疑的地方是您将int destLen作为uLongf类型的输出参数提供。如果uLongf大于int,这可能会破坏您的堆栈,并且"长"部分表明在64位平台上可能会出现这种情况。

我建议您立即将destLen声明为uLongf类型,并避免强制转换。

除此之外,我看不出你的代码有任何问题。