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 3093

Summary: Memory Leak in TTF_RenderUTF8_Blended_Wrapped
Product: SDL_ttf Reporter: Pankaj <p.sangra>
Component: miscAssignee: Sam Lantinga <slouken>
Status: RESOLVED FIXED QA Contact: Sam Lantinga <slouken>
Severity: normal    
Priority: P2 CC: amit.jain83, philipp.wiesemann
Version: 2.0.12   
Hardware: All   
OS: All   
Attachments: Freeing the allocated memory in failure case

Description Pankaj 2015-08-14 11:54:14 UTC
Hi Mr.Sam,
Actually I am using SDL_ttf. When I was looking inside the code.
I have found that in function "SDL_Surface *TTF_RenderUTF8_Blended_Wrapped(TTF_Font *font, const char *text, SDL_Color fg, Uint32 wrapLength)"
It is allocating "str" then allocating "strLines". If "strLines" fails to allocate, error for out of memory is set and returned NULL. But memory allocated for "str" is not freed. There should be code for freeing the memory allocated to "str" in do-while loop where NULL has returned for allocating "strLines"

Current code in SDL2_ttf-2.0.12 version:

SDL_Surface *TTF_RenderUTF8_Blended_Wrapped(TTF_Font *font, const char *text, SDL_Color fg, Uint32 wrapLength)
{
	//some code
	str = SDL_stack_alloc(char, str_len+1);
	//some code
	strLines = (char **)SDL_realloc(strLines, (numLines+1)*sizeof(*strLines));
	if (!strLines) {
		TTF_SetError("Out of memory");
        return(NULL);
    }
	//some code
}

Code with fix:

SDL_Surface *TTF_RenderUTF8_Blended_Wrapped(TTF_Font *font, const char *text, SDL_Color fg, Uint32 wrapLength)
{
	//some code
	str = SDL_stack_alloc(char, str_len+1);
	//some code
	strLines = (char **)SDL_realloc(strLines, (numLines+1)*sizeof(*strLines));
	if (!strLines) {
		TTF_SetError("Out of memory");
		SDL_stack_free(str);
        return(NULL);
    }
	//some code
}


Regards,
Pankaj
Comment 1 Philipp Wiesemann 2015-08-15 19:40:16 UTC
Additionally, if the realloc() would fail then the old strLines would not be freed.
Comment 2 Amit Jain 2015-08-21 09:38:04 UTC
Created attachment 2249 [details]
Freeing the allocated memory in failure case

Patch has been attached for solution

Explanation:
In function "SDL_Surface *TTF_RenderUTF8_Blended_Wrapped(TTF_Font *font, const char *text, SDL_Color fg, Uint32 wrapLength)"
It is allocating "str" then allocating "strLines". If "strLines" fails to allocate, error for out of memory is set and returned NULL. But memory allocated for "str" is not freed. There should be code for freeing the memory allocated to "str" in do-while loop where NULL has returned for allocating "strLines"
Comment 3 Sam Lantinga 2017-09-10 06:22:21 UTC
Fixed, thanks!
https://hg.libsdl.org/SDL_ttf/rev/36787734aedf