From 11b8dd76db8145165352d93b4f77ac265d890341 Mon Sep 17 00:00:00 2001 From: Sam Lantinga Date: Sun, 14 Sep 2025 08:22:37 -0700 Subject: [PATCH] Fixed memory leak when using detached threads Fixes https://github.com/libsdl-org/SDL/issues/13886 (cherry picked from commit ede86a1267f58f931f9d2207b342eb4ba9906f0f) --- src/thread/SDL_thread.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/thread/SDL_thread.c b/src/thread/SDL_thread.c index 99cb9dd7f1..d9180f5267 100644 --- a/src/thread/SDL_thread.c +++ b/src/thread/SDL_thread.c @@ -333,7 +333,7 @@ void SDL_RunThread(SDL_Thread *thread) // Mark us as ready to be joined (or detached) if (!SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_COMPLETE)) { // Clean up if something already detached us. - if (SDL_GetThreadState(thread) == SDL_THREAD_DETACHED) { + if (SDL_GetAtomicInt(&thread->state) == SDL_THREAD_DETACHED) { SDL_free(thread->name); // Can't free later, we've already cleaned up TLS SDL_free(thread); } @@ -487,11 +487,10 @@ void SDL_DetachThread(SDL_Thread *thread) return; } - // The thread may vanish at any time, it's no longer valid - SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false); - // Grab dibs if the state is alive+joinable. if (SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_DETACHED)) { + // The thread may vanish at any time, it's no longer valid + SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false); SDL_SYS_DetachThread(thread); } else { // all other states are pretty final, see where we landed.