🔧 Fix memory leak in pthread init functions on failure

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.
This commit is contained in:
Ryan Lefkowitz 2025-09-15 18:20:01 -04:00
parent 98d2b90e82
commit c59812e558

View 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)); *mutex = (pthread_mutex_t*)ZSTD_malloc(sizeof(pthread_mutex_t));
if (!*mutex) if (!*mutex)
return 1; 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) 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)); *cond = (pthread_cond_t*)ZSTD_malloc(sizeof(pthread_cond_t));
if (!*cond) if (!*cond)
return 1; 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) int ZSTD_pthread_cond_destroy(ZSTD_pthread_cond_t* cond)