From c59812e558dd6ba24f592c77662204b721bb1dbb Mon Sep 17 00:00:00 2001 From: Ryan Lefkowitz Date: Mon, 15 Sep 2025 18:20:01 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20Fix=20memory=20leak=20in=20pthre?= =?UTF-8?q?ad=20init=20functions=20on=20failure?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When pthread_mutex_init() or pthread_cond_init() fails in the debug implementation (DEBUGLEVEL >= 1), the previously allocated memory was not freed, causing a memory leak. This fix ensures that allocated memory is properly freed when pthread initialization functions fail, preventing resource leaks in error conditions. The issue affects: - ZSTD_pthread_mutex_init() at lib/common/threading.c:146 - ZSTD_pthread_cond_init() at lib/common/threading.c:167 This is particularly important for long-running applications or scenarios with resource constraints where pthread initialization might fail due to system limits. --- lib/common/threading.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/common/threading.c b/lib/common/threading.c index 25bb8b981..1d5c97d3c 100644 --- a/lib/common/threading.c +++ b/lib/common/threading.c @@ -143,7 +143,14 @@ int ZSTD_pthread_mutex_init(ZSTD_pthread_mutex_t* mutex, pthread_mutexattr_t con *mutex = (pthread_mutex_t*)ZSTD_malloc(sizeof(pthread_mutex_t)); if (!*mutex) return 1; - return pthread_mutex_init(*mutex, attr); + { + int const ret = pthread_mutex_init(*mutex, attr); + if (ret != 0) { + ZSTD_free(*mutex); + *mutex = NULL; + } + return ret; + } } int ZSTD_pthread_mutex_destroy(ZSTD_pthread_mutex_t* mutex) @@ -164,7 +171,14 @@ int ZSTD_pthread_cond_init(ZSTD_pthread_cond_t* cond, pthread_condattr_t const* *cond = (pthread_cond_t*)ZSTD_malloc(sizeof(pthread_cond_t)); if (!*cond) return 1; - return pthread_cond_init(*cond, attr); + { + int const ret = pthread_cond_init(*cond, attr); + if (ret != 0) { + ZSTD_free(*cond); + *cond = NULL; + } + return ret; + } } int ZSTD_pthread_cond_destroy(ZSTD_pthread_cond_t* cond)