From 3923daf5513b632dc29255a50a259d62759681b0 Mon Sep 17 00:00:00 2001 From: C-3PO Date: Tue, 31 Jul 2018 13:38:21 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fix=20inflate=20error=20(output?= =?UTF-8?q?=20ended=20prematurely)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/inflate.c | 4 +++- src/inflate.h | 1 + src/main.c | 8 +++++++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/inflate.c b/src/inflate.c index 49f7011..f9c4aac 100644 --- a/src/inflate.c +++ b/src/inflate.c @@ -48,6 +48,7 @@ struct InflateOutput inflateInflate(unsigned long numInputBytes, bool hasMoreByt uncomprBufferNext = uncomprBuffer; struct InflateOutput out; + out.hasReachedEnd = false; while (remainingInput > 0 && spaceInOutput > 0) { in_bytes = remainingInput; @@ -74,6 +75,7 @@ struct InflateOutput inflateInflate(unsigned long numInputBytes, bool hasMoreByt if (status <= TINFL_STATUS_DONE) { if (status == TINFL_STATUS_DONE) { // Decompression completed successfully. + out.hasReachedEnd = true; break; } else { // Decompression failed. @@ -82,7 +84,7 @@ struct InflateOutput inflateInflate(unsigned long numInputBytes, bool hasMoreByt } } - //If output buffer is filled + //If output buffer is filled, we need to clear it before decompressing more data if (spaceInOutput == 0) { break; } diff --git a/src/inflate.h b/src/inflate.h index 395a4ec..d557a9b 100644 --- a/src/inflate.h +++ b/src/inflate.h @@ -4,6 +4,7 @@ void inflateInit(char* comprBuffer, char* uncomprBuffer, unsigned long uncomprBu struct InflateOutput { bool needMoreInput; + bool hasReachedEnd; unsigned long numBytesWrittenToOutput; }; diff --git a/src/main.c b/src/main.c index 55fd357..569345f 100644 --- a/src/main.c +++ b/src/main.c @@ -58,6 +58,8 @@ int main(int argc, unsigned char *argv[]) { fprintf(stderr, "Could not allocate %lu bytes for uncompressed buffer.\n", BUFFER_SIZE); exit(1); } + memset(compressedChunk, 0, BUFFER_SIZE); + memset(uncompressedChunk, 0, BUFFER_SIZE); //------------------------------------------------- @@ -90,10 +92,12 @@ int main(int argc, unsigned char *argv[]) { //Read actual file unsigned long remainingBytes = fileLength; bool needToRead = true; + bool hasReachedEnd = false; unsigned long chunkSize; - while (remainingBytes > 0) { + while (remainingBytes > 0 || !hasReachedEnd) { if (needToRead) { chunkSize = min(BUFFER_SIZE, remainingBytes); + memset(compressedChunk, 0, chunkSize); getBytes(compressedChunk, chunkSize); remainingBytes -= chunkSize; @@ -106,8 +110,10 @@ int main(int argc, unsigned char *argv[]) { //Decompress file //bytes are contained in uncompressedChunk from [0, inflateResult.numBytesWrittenToOutput - 1] + memset(uncompressedChunk, 0, BUFFER_SIZE); inflateResult = inflateInflate(needToRead ? chunkSize : 0, remainingBytes > 0); needToRead = inflateResult.needMoreInput; + hasReachedEnd = inflateResult.hasReachedEnd; write(1, uncompressedChunk, inflateResult.numBytesWrittenToOutput);