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

My code produces junk while uncompressing

我写了一个简单的程序来测试 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▒й! 的内容?字符串末尾的垃圾不同于 运行 运行.

auto uncompressed = new char[length];

因为这个 uncompressed 数组不是空终止的。试试下面的代码:

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