]> git.ipfire.org Git - thirdparty/zstd.git/commitdiff
🔧 Fix memory leak in pthread init functions on failure 4486/head
authorRyan Lefkowitz <rlefkowitz1800@yahoo.com>
Mon, 15 Sep 2025 22:20:01 +0000 (18:20 -0400)
committerRyan Lefkowitz <rlefkowitz1800@yahoo.com>
Mon, 15 Sep 2025 22:20:01 +0000 (18:20 -0400)
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

index 25bb8b981042d8637df0d4eb45100f85487e4aad..1d5c97d3cea8400b307792d4069c7d7a6f8a2fd1 100644 (file)
@@ -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)