From cebae4d1f876b95c5f58c9a12d23a78bf04c08d8 Mon Sep 17 00:00:00 2001 From: Juniper Tyree <50025784+juntyr@users.noreply.github.com> Date: Tue, 10 Dec 2024 13:28:29 +0200 Subject: [PATCH 1/2] Fix UB for small array compression --- include/SZ3/api/sz.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/include/SZ3/api/sz.hpp b/include/SZ3/api/sz.hpp index c8370912..364b24a1 100644 --- a/include/SZ3/api/sz.hpp +++ b/include/SZ3/api/sz.hpp @@ -92,7 +92,8 @@ template char *SZ_compress(const SZ3::Config &config, const T *data, size_t &cmpSize) { using namespace SZ3; - size_t bufferLen = 2 * config.num * sizeof(T); + size_t bufferLen = config.size_est() + 2 * config.num * sizeof(T); + bufferLen = (bufferLen < 1024) ? 1024 : bufferLen; auto buffer = new char[bufferLen]; cmpSize = SZ_compress(config, data, buffer, bufferLen); From 0f3dde7788863e84383f8efb06cdc3931b5c36d6 Mon Sep 17 00:00:00 2001 From: Juniper Tyree <50025784+juntyr@users.noreply.github.com> Date: Tue, 10 Dec 2024 15:23:02 +0200 Subject: [PATCH 2/2] Ensure lossless fallback always has enough space --- include/SZ3/api/sz.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/SZ3/api/sz.hpp b/include/SZ3/api/sz.hpp index 364b24a1..7236a4b1 100644 --- a/include/SZ3/api/sz.hpp +++ b/include/SZ3/api/sz.hpp @@ -92,8 +92,8 @@ template char *SZ_compress(const SZ3::Config &config, const T *data, size_t &cmpSize) { using namespace SZ3; - size_t bufferLen = config.size_est() + 2 * config.num * sizeof(T); - bufferLen = (bufferLen < 1024) ? 1024 : bufferLen; + // Ensure that the buffer can always hold the config and the lossless fallback + size_t bufferLen = config.size_est() + ZSTD_compressBound(config.num * sizeof(T)); auto buffer = new char[bufferLen]; cmpSize = SZ_compress(config, data, buffer, bufferLen);