我的代码在解压缩时产生垃圾

时间:2018-03-13 10:08:53

标签: c++ zlib

我编写了一个简单的程序来测试zlib compress()uncompress()函数:

#include <iostream>
#include <string>

#include "zlib.h"

using namespace std;

int main()
{
    string str = "Hello Hello Hello Hello Hello Hello!";
    size_t length = str.length();
    size_t newLength = compressBound(length);
    auto compressed = new char[newLength];
    if (compress((Bytef*)compressed, (uLongf*)&newLength, (const Bytef*)str.c_str(), length) != Z_OK)
    {
        throw runtime_error("Error while compressing data");
    }

    auto uncompressed = new char[length];
    if (uncompress((Bytef*)uncompressed, (uLongf*)&length, (Bytef*)compressed, newLength) != Z_OK)
    {
        throw runtime_error("Error while uncompressing data");
    }

    cout << uncompressed;

    delete[] compressed;
    delete[] uncompressed;
    return 0;
}

为什么此程序会打印Hello Hello Hello Hello Hello Hello!¤¤¤¤&У3▒й!之类的内容?字符串末尾的垃圾与运行不同。

1 个答案:

答案 0 :(得分:2)

auto uncompressed = new char[length];

因为此uncompressed数组未终止。请尝试以下代码:

cout << std::string(uncompressed, length) << endl;