We are currently migrating Bugzilla to GitHub issues.
Any changes made to the bug tracker now will be lost, so please do not post new bugs or make changes to them.
When we're done, all bug URLs will redirect to their equivalent location on the new bug tracker.

Bug 150

Summary: memory leak in SDL_thread.c
Product: SDL Reporter: Danijel Kopcinovic <danijel.kopcinovic>
Component: threadAssignee: Ryan C. Gordon <icculus>
Status: RESOLVED FIXED QA Contact: Sam Lantinga <slouken>
Severity: normal    
Priority: P2 CC: support
Version: 1.2.9   
Hardware: x86   
OS: Windows (All)   

Description Danijel Kopcinovic 2006-02-22 09:04:17 UTC
In routine SDL_DelThread, I got a memory leak. It was due to not freeing thread lock if there were no more threads. Here is my fix for this:
static void SDL_DelThread(SDL_Thread *thread)
{
	int i;

	if ( thread_lock ) {
		SDL_mutexP(thread_lock);
		for ( i=0; i<SDL_numthreads; ++i ) {
			if ( thread == SDL_Threads[i] ) {
				break;
			}
		}
		if ( i < SDL_numthreads ) {
			if ( --SDL_numthreads > 0 ) {
				while ( i < SDL_numthreads ) {
					SDL_Threads[i] = SDL_Threads[i+1];
					++i;
				}
			} else {
				SDL_maxthreads = 0;
				free(SDL_Threads);
				SDL_Threads = NULL;
			}
#ifdef DEBUG_THREADS
			printf("Deleting thread (%d left - %d max)\n",
					SDL_numthreads, SDL_maxthreads);
#endif
		}
		SDL_mutexV(thread_lock);

    //  Added by Danijel Kopcinovic as a fix for memory leak (thread_lock was
    //  not deleted if there were no more threads).
    if (SDL_Threads == NULL) SDL_ThreadsQuit();
	}
}
Comment 1 Dmitry Yakimov 2006-02-28 00:01:24 UTC
Shall we did it in atexit?
Comment 2 Sam Lantinga 2006-03-09 10:34:39 UTC
(In reply to comment #1)
> Shall we did it in atexit?
> 

No, there are lots of issues with atexit:
* There may not be any C runtime
* The C runtime of the SDL library may be different from that of the application
* SDL may be dynamically loaded and then unloaded which would cause a crash at exit
* There's no guarantee that threads won't persist past our atexit call and be cleaned up in a subsequent atexit handler.
Comment 3 Sam Lantinga 2006-03-11 20:18:31 UTC
This is fixed in CVS, thanks!