From ef705d3ac6ed72e42455f238674e7af8ea8f98b2 Mon Sep 17 00:00:00 2001 From: cottongin Date: Thu, 29 Jan 2026 18:54:01 -0500 Subject: [PATCH] Fix zip dictionary allocation --- lib/ZipFile/ZipFile.cpp | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/lib/ZipFile/ZipFile.cpp b/lib/ZipFile/ZipFile.cpp index a5f65ea..067582a 100644 --- a/lib/ZipFile/ZipFile.cpp +++ b/lib/ZipFile/ZipFile.cpp @@ -529,10 +529,24 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch } if (fileStat.method == MZ_DEFLATED) { - // Setup inflator + // Allocate largest buffer first to maximize chance of finding contiguous block + // Dictionary buffer (32KB) - needed for DEFLATE sliding window + const auto outputBuffer = static_cast(malloc(TINFL_LZ_DICT_SIZE)); + if (!outputBuffer) { + Serial.printf("[%lu] [ZIP] Failed to allocate memory for dictionary (need %d bytes)\n", millis(), + TINFL_LZ_DICT_SIZE); + if (!wasOpen) { + close(); + } + return false; + } + memset(outputBuffer, 0, TINFL_LZ_DICT_SIZE); + + // Setup inflator (~11KB) const auto inflator = static_cast(malloc(sizeof(tinfl_decompressor))); if (!inflator) { Serial.printf("[%lu] [ZIP] Failed to allocate memory for inflator\n", millis()); + free(outputBuffer); if (!wasOpen) { close(); } @@ -541,29 +555,18 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch memset(inflator, 0, sizeof(tinfl_decompressor)); tinfl_init(inflator); - // Setup file read buffer + // Setup file read buffer (smallest allocation last) const auto fileReadBuffer = static_cast(malloc(chunkSize)); if (!fileReadBuffer) { Serial.printf("[%lu] [ZIP] Failed to allocate memory for zip file read buffer\n", millis()); free(inflator); + free(outputBuffer); if (!wasOpen) { close(); } return false; } - const auto outputBuffer = static_cast(malloc(TINFL_LZ_DICT_SIZE)); - if (!outputBuffer) { - Serial.printf("[%lu] [ZIP] Failed to allocate memory for dictionary\n", millis()); - free(inflator); - free(fileReadBuffer); - if (!wasOpen) { - close(); - } - return false; - } - memset(outputBuffer, 0, TINFL_LZ_DICT_SIZE); - size_t fileRemainingBytes = deflatedDataSize; size_t processedOutputBytes = 0; size_t fileReadBufferFilledBytes = 0;