Count Zero
Count Zero

Reputation: 545

My code produces junk while uncompressing

I've written a simple program to test zlib compress() and uncompress() functions:

#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;
}

Why this program prints something like Hello Hello Hello Hello Hello Hello!¤¤¤¤&У3▒й!? The junk at the end of the string differs from run to run.

Upvotes: 0

Views: 71

Answers (1)

for_stack
for_stack

Reputation: 22906

auto uncompressed = new char[length];

Because this uncompressed array is NOT null terminated. Try the following code:

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

Upvotes: 2

Related Questions