Search code examples
c++zlibcompression

Unhandled exception while using zlib uncompress()


I am having some problems performing uncompression with zlib uncompress() function. The file that I compressed, which is being passed as fileSource to uncompressFile(), didn't throw me a runtime exception and worked perfectly fine. What I am doing basically is reading the bytes from a file, with fread, and then storing it in a buffer and then compressing/decompressing. My uncompress function:

    bool unCompressFile(const char* fileSource, const char* fileDestination) {
        std::cout << "\nFilesize: " << fileSize << std::endl << "compressedSize: " << compressedSize << std::endl;
        // Test printout: fileSize = 164008 && compressedSize = 77778
        // These were the values from a test program
        char* bufferSource = new char[(sizeof(char) * compressedSize + 1)]; 
        if (!bufferSource) {
          std::cout << "Error allocating memory \n"; return false; 
        }
        // Reading from previously compressed file
        FILE* inputFile = NULL;
        inputFile = fopen(fileSource, "rb");
        if (!inputFile) { return false; } // Error handling

        if (!fread(bufferSource, compressedSize, 1, inputFile)) {
            fclose(inputFile);
            delete[] bufferSource;
            return false;
        }
        fclose(inputFile);

        uLong destinationLen = fileSize;
        Bytef* bufferDestination = new Bytef[fileSize + 1];
        int result = uncompress(bufferDestination, &destinationLen, (const Bytef*)bufferSource, compressedSize); // Here is the error

        fclose(outputFile);

        delete[] bufferSource;
        delete[] bufferDestination;

        return true;

    }

The string fileSource is the path to an already compressed file and fileDestination would be the output, which I use fwrite(omitted here). Both compressedSize and fileSize are global variables. The value of fileSize is the length in bytes of the original file and compressedSize is the size of the compressed data(modified by compress()). Exception occurs at the uncompress function else no error print shows up. I can't see what is causing this runtime error.

EDIT 1: I tried with compress2(), and for the compression level I tried 0 (none) so basically with no compression and my unCompressFile function did work. Something is messing up the decompression but I can't figure it out.

EDIT 2: First 30 bytes of the compressed file:

78 9C EC B9 77 54 53 4D F4 2E 7C D2 03 84 10 31 90 84 1A A4 2B 1D 04 14 84 D0 51 EA 2B 55

Solution

  • Disable ASM686 option to avoid this or other kind of errors when building zlib. As Mark Adler said:

    Those are third-party contributions to zlib and are not supported. Due to reported issues with both the compression and decompression assembler code, I plan to remove them from the contrib directory in the next version.